Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 查找长列表Python中所有元素组合的最有效方法_Python 3.x_List_Out Of Memory_Combinations_Long Integer - Fatal编程技术网

Python 3.x 查找长列表Python中所有元素组合的最有效方法

Python 3.x 查找长列表Python中所有元素组合的最有效方法,python-3.x,list,out-of-memory,combinations,long-integer,Python 3.x,List,Out Of Memory,Combinations,Long Integer,抱歉,标题看起来有点牵强。我被要求计算列表中2个或更多元素的总和。我在网上搜索了一下,我找到了一些结果,我测试了一下,但是没有用 input.txt 35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576 代码.py from itertools import combinations def combo(arr, r): return list(combinations(arr, r)) with

抱歉,标题看起来有点牵强。我被要求计算列表中2个或更多元素的总和。我在网上搜索了一下,我找到了一些结果,我测试了一下,但是没有用

input.txt

35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
代码.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中查找长列表中元素组合的最有效方法是什么”。

您可以尝试通过不将
itertools.compositions的输出转换为列表,而只是迭代生成器输出来节省内存:

for rr in range(2, 22):
    print(f"combine {rr} values")
    for c in itertools.combinations(values, rr):
        if sum(c) == 127:
            print(c)
检查: