可能金额的功能不会超过一次

Function for possible sums not going more than once

我正在编写一个程序来获取数字列表中所有可能的总和。可能的总和会将总和分成两组,即高于和低于另一个给定数字的那些。到目前为止,这是我的代码:

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

while 循环的前半部分 运行s 如预期的那样,但是当我继续执行程序时(更具体地说是通过部分打印 resulta 和 mcadam),我得到一个错误,指出该组结果是空的。请记住下面的代码将使用组中的第一个数字 'tableheight' 执行,它等于 1000。这是程序为 运行 时打印的内容(我也在每个旁边注释了输出指的是):

[(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
>>> 

当数字大于 1000 时出现问题。任何帮助都将是巨大的,谢谢!

正如评论中所说,您找不到任何总和大于 1000 的组合。这是由于 itertools.combinations 没有两次使用 iterable 的任何元素。

为了解决这个问题,您应该使用允许多次使用可迭代元素的版本:itertools.combinations_with_replacement.
有关详细信息,请查看 python 文档,网址为:https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement