Answer to Question #176560 in Python for CHANDRASENA REDDY CHADA

Question #176560

Triplet Sum

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).Input


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.Explanation


When the given array is [0, 1, 2, 3, 5, 7, 13, 17, 19, 19] and the required sum is 22, the triplets (0, 3, 19), (0, 5, 17), (1, 2, 19), (2, 3, 17) and (2, 7, 13) have the given sum 22.


Sample Input 1

0 12 17 8 9 21

29


Sample Output 1

(0, 8, 21)

(0, 12, 17)

(8, 9, 12)


Sample Input 2

0 1 2 3 5 7 13 17 19 19

22


Sample Output 2

(0, 3, 19)

(0, 5, 17)

(1, 2, 19)

(2, 3, 17)

(2, 7, 13)


The outputs should be exactly as shown in the above samples else test cases not satisfying.

please help me.


1
Expert's answer
2021-03-30T03:10:42-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)))


if len(triplets)!=0:
    for triplet in triplets:
        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
APPROVED BY CLIENTS