简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM