函数的可能和不超过

2024-09-25 08:40:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序来计算一系列数字的所有可能的和。可能的总和将把总和分成两组,即高于和低于另一给定数字的总和。这是我目前的代码:

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循环的前半部分按预期运行,但是当我继续执行程序时(更具体地说是通过打印resulta和mcadam的部分),我得到一个错误,指出resulta组是空的。请记住以下代码将使用组“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(mcadam))
ValueError: min() arg is an empty sequence
>>> 

当数字要大于1000时,出了点问题。任何帮助都是巨大的,谢谢!你知道吗


Tags: inforlen数字resultseqsumprint
1条回答
网友
1楼 · 发布于 2024-09-25 08:40:45

正如在一篇评论中所说的,你找不到任何总和大于1000的组合。这是因为itertools.combinations没有两次使用iterable的任何元素。你知道吗

为了克服这个问题,您应该使用允许iterable中元素的多种用法的版本:itertools.combinations_with_replacement
有关更多信息,请查看python文档:https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement

相关问题 更多 >