Home > Back-end >  Combination sum higher than and lower than
Combination sum higher than and lower than

Time:09-23

im now starting in programing. I get one exercise to generate a combination of 10 numbers with a set of numbers, and make a sum and the sum of that numbers need to be less than 800 and higher than 700, and print the result and combination (Print All combinations).

For example if the set of numbers is 10,20,30,40,50,60,70,80,90,100 and i need to generate a set of 10 numbers using the numbers i set and the sum of that combination need to be less 560 and higher than 500.

10 20 30 40 50 60 70 80 90 100 = 550
10 20 30 40 50 40 100 80 90 90 = 550
..

I start a code in Python, but im little stuck, how i can sum the combinations.

import itertools

myList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in range(len(myList)):
    for combinations in itertools.combinations(myList, i):
        print(combinations)

sum(e for e in combinations if e >= 550)

CodePudding user response:

You're very close, but you need to filter based on whether sum(e) is in the desired range, not whether e itself is.

>>> from itertools import combinations
>>> myList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> [e for i in range(len(myList)) for e in combinations(myList, i) if 500 < sum(e) < 560]
[(20, 40, 50, 60, 70, 80, 90, 100), (30, 40, 50, 60, 70, 80, 90, 100), (10, 20, 30, 50, 60, 70, 80, 90, 100), (10, 20, 40, 50, 60, 70, 80, 90, 100), (10, 30, 40, 50, 60, 70, 80, 90, 100), (20, 30, 40, 50, 60, 70, 80, 90, 100)]

CodePudding user response:

combinations only exists inside your inner for loop - you can sum it right after you print it simply with sum(combinations). Your sum() statement is outside the loop, where combinations is no longer defined.

Something like:

import itertools

myList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in range(len(myList)):
    for combinations in itertools.combinations(myList, i):
        if 500 < sum(combinations) < 560:
            print(combinations, sum(combinations))
  • Related