Reputation: 78
I'm writing a program to take every possible sum of a list of numbers. The possible sums will split the sums into two groups, those that are above and below another given number. This is my code so far:
import itertools
a = 0
tableheight = [1000, 2000]
cointhick = [50, 100, 200, 400]
while a < len(tableheight):
result = [seq for i in range(len(cointhick), 0, -1) for seq in itertools.combinations(cointhick, i) if sum(seq) <= tableheight[a]]
great = []
b = 0
while b < len(result):
great.append(sum(result[b]))
b += 1
print(result)
print(great)
print(max(great))
resulta = [seq for i in range(len(cointhick), 0, -1) for seq in itertools.combinations(cointhick, i) if sum(seq) >= tableheight[a]]
list = []
c = 0
while c < len(resulta):
list.append(sum(resulta[c]))
c += 1
print(resulta)
print(list)
print(min(list))
a += 1
The first half of the while loop runs as expected, however when I proceed with the program (more specifically through the portion printing resulta and mcadam), I get an error, stating that the group of resulta is empty. Please keep in mind the below code will be executed using the first number in the group 'tableheight', which is equal to 1000. Here's what is printed when the program is run (I also commented next to what each output refers to):
[(50, 100, 200, 400), (50, 100, 200), (50, 100, 400), (50, 200, 400), (100, 200, 400), (50, 100), (50, 200), (50, 400), (100, 200), (100, 400), (200, 400), (50,), (100,), (200,), (400,)] # All possible sums using numbers in group 'cointhick' that when added will be less than 1000 #
[750, 350, 550, 650, 700, 150, 250, 450, 300, 500, 600, 50, 100, 200, 400] # Results of sums used in each tuple in above list #
750 # The maximum sum found in the above list #
[] # The list of sums that when added will be greater than 1000
[] # The result of the sums found in the above list
Traceback (most recent call last):
File "C:\Users\Owner\Desktop\Renamable Programs\thing.py", line 23, in <module>
print(min(list))
ValueError: min() arg is an empty sequence
>>>
Something is going wrong when the numbers are to be greater than 1000. Any help on this will be huge, thank you!
Upvotes: 3
Views: 69
Reputation: 629
As it was said in a comment, you do not find any combination whose sum is greater than 1000. This is due to itertools.combinations
not using any element of the iterable twice.
To get past this problem, you should rather use the version that allows for multiple usages of elements in the iterable : itertools.combinations_with_replacement
.
For more information, check the python doc at : https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement
Upvotes: 1