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 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 K
Output
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.
Test Case 1
Input
0 12 17 8 9 21
29
Output
(0, 8, 21)
(0, 12, 17)
(8, 9, 12)
Test Case 2
Input
0 1 2 3 5 7 13 17 19 19
22
Output
(0, 3, 19)
(0, 5, 17)
(1, 2, 19)
(2, 3, 17)
(2, 7, 13)
We need all two test cases can be came when code was run. I want exact outputs for all test cases
arr = [int(num) for num in input().split()]
K = int(input())
tripls = list()
for i, num1 in enumerate(arr):
for j, num2 in enumerate(arr[i+1:], i+1):
for num3 in arr[j+1:]:
if num1 + num2 + num3 == K:
t = [num1, num2, num3]
t.sort()
tripls.append(tuple(t))
tripls = set(tripls)
if tripls:
for tripl in sorted(tripls):
print(tripl)
else:
print('No Matching Triplets Found')
Comments
Leave a comment