【发布时间】:2019-12-17 11:11:19
【问题描述】:
我想定义一个接受以下参数的函数: - 一个数字列表 - 最低限度 - 最大值
它应该返回一个列表(或集合)列表,其中每个列表的总和在最小值和最大值之间。列表中不应有重复项。
我所拥有的并没有返回所有可能的列表:
def givelists(List, minimum, maximum):
currentlist = [] #list to keep track of sum of currently included subset of list
listoflist = [] #list of all lists of which the sum is between specified minumum and maximum
for number in List:
if minimum < (sum(currentlist) + number) < maximum:
currentlist.append(number)
listoflist.append(currentlist)
currentlist = []
elif (sum(currentlist) + number) < minimum:
currentlist.append(number)
else:
if number in range(minimum, maximum):
listoflist.append(number)
return(listoflist)
例如:
givelists(list(range(1,6)), 2, 8)
# Output: [[1, 2], [3], [4], [5]]
【问题讨论】:
-
你期待什么结果?使用
range(1,2), 1, 1对其进行测试。你会期待什么? -
对于您示例的输出,我会说 [ [3], [4], [5], [1,2], [1,3], [1,4], [1,5], [2,3]..... ] 这是总和在 2 到 8 之间的所有可能组合。那么你能重新制定预期的输出吗?
-
请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?
标签: python algorithm list combinations