Answer to Question #211581 in Python for sudheer

Question #211581

Given an array n integers, find and print all the unique triplets (a, b, c) in the array which give the sum K. (a+b+c=K).

The first line of the input will be space separated integers, denoting the elements of the array. The second line of the input will be an integer denoting the required sum KOutput


The output should be multiple lines, each line containing a unique triplet. The elements of the triple must be sorted in increasing order and all the triplets printed must be sorted in increasing order. Print "No Matching Triplets Found" if there are no triplets with the given sum.

input: 0 12 17 8 9 21

22

ouput:(0, 8, 21)

(0, 12, 17)

(8, 9, 12) should be like this


1
Expert's answer
2021-06-29T00:16:29-0400


integers = [int(number) for number in input("Enter array of integers: ").split()]
K = int(input("K = "))



triplets = []



for i in range(len(integers)):
    for j in range(i+1,len(integers)):
        for k in range(j+1, len(integers)):
            
            a = integers[i]
            b = integers[j]
            c = integers[k]



            if a+b+c == K:
                triplets.append(tuple((a,b,c)))
#sorting every item in triplet
sorted_triplets=[]
for tripl in triplets:
    item = sorted(tripl)
    sorted_triplets.append(item)


#sorting the whole triplets
triplets= sorted(sorted_triplets)
if len(triplets)!=0:
    for triplet in triplets:
        triplet=sorted(triplet)
        print(triplet)



else:
    print("No Matching Triplets Found")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS