Answer to Question #210482 in Python for Sudheer

Question #210482

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 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")

Output:(0, 12, 17)

(0, 8, 21)

(12, 8, 9)

The outout should be like this:(0, 8, 21)

(0, 12, 17)

(8, 9, 12)




1
Expert's answer
2021-06-24T14:24:32-0400
def find_triplets(integers, K):
    n = len(integers)
    triplets = []
    for i in range(0, n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                triplet = (integers[i], integers[j], integers[k])
                if sum(triplet) == K:
                    triplets.append(triplet)
    return triplets


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

result = find_triplets(integers_arr, K)
if result:
    [print(triplet) for triplet in result]
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