【发布时间】:2021-05-21 07:00:08
【问题描述】:
抱歉,标题看起来有点牵强。我被要求计算列表中 2 个或更多元素的总和。我在网上搜索了一下,找到了一些结果,我测试了它们,但是没有用...
输入.txt
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
code.py
from itertools import combinations
def combo(arr, r):
return list(combinations(arr, r))
with open("input.txt") as f:
nums = f.read().split("\n")
nums = [int(item) for item in nums]
r = range(2,20)
for rr in r:
for c in combo(nums, rr):
if sum(c) == 127:
print(c)
它在上面的代码中有效,因为列表很短。但是,我收到的input.txt 有 100 行长!在这种情况下,Python 抛出了 MemoryError。所以我需要找到更好的方法。不幸的是,我没有找到任何其他方法,除了更长的方法,所以我问了一个问题,“在 Python 中找到长列表中元素组合的最有效方法是什么”。
【问题讨论】:
标签: python-3.x list out-of-memory combinations long-integer