我正在编写一个程序来获取每个数字列表的总和。可能的总和将把总和分成两组,即高于和低于另一给定数字的组。到目前为止,这是我的代码:
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]]
mcadam = []
c = 0
while c < len(resulta):
mcadam.append(sum(resulta[c]))
c += 1
print(resulta)
print(mcadam)
print(min(mcadam))
a += 1
while循环的前半部分按预期运行,但是当我继续执行程序时(更具体地说是通过打印结果和mcadam部分),我得到一个错误,说明结果组是空的。请记住,下面的代码将使用“tableheight”组中的第一个数字执行,该数字等于1000.这是程序运行时打印的内容(我还在每个输出引用的内容旁边注释):< / p>
[(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(mcadam))
ValueError: min() arg is an empty sequence
>>>
当数字大于1000时出现问题。对此有任何帮助都很大,谢谢!
答案 0 :(得分:1)
正如在评论中所说,你找不到总和大于1000的任何组合。这是由于itertools.combinations
没有使用迭代的任何元素两次。
要解决此问题,您应该使用允许迭代中多个元素用法的版本:itertools.combinations_with_replacement
。
有关更多信息,请查看python doc:https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement