Skip to content
Advertisement

Find three numbers from a list that add up to a specific number

How can I adjust the below code to find three numbers instead of two numbers yielding the target amount? I’ve already came across the code below from another question titled “Find two numbers from a list that add up to a specific number”. Thank you.

numbers = [2, 4, 6, 8, 10] #revised so that 3 numbers add up to 12
target_number = 12


for i, number in enumerate(invoices[:-1]):  
    complementary = target_number - number
    if complementary in invoices[i+1:]:  number, complementary))
        break
else: 
    print("No solutions exist")

Advertisement

Answer

If the numbers list is relatively small, you can use the itertools combinations function from the Python standard library.

import itertools

numbers = [2, 4, 6, 8, 10]
target_number = 12

print([i for i in itertools.combinations(numbers, 3) if sum(i) == target_number])

Which gives the result:

[(2, 4, 6)]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement