Reputation: 81
Sorry the title looks a little far-fetched. I was asked to calculate the sum of 2 or more elements in a list. I searched it up on the web, I found some results, I tested them, but it didn't work...
input.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)
It works in the code above, it works because the list is quite short. However, the input.txt
I recieved was 100 lines long! In that case, Python threw a MemoryError. So I needed to find a better way. Unfortunately, I didn't find any other way, except a longer way, so I ask the question, "What is the most effient way to find the combination of elements in a long list in Python".
Upvotes: 0
Views: 422
Reputation: 3472
You can try to save memory by not converting the output of itertools.combinations
to a list and instead just iterating over the generator output:
for rr in range(2, 22):
print(f"combine {rr} values")
for c in itertools.combinations(values, rr):
if sum(c) == 127:
print(c)
Check: Making all possible combinations of a list
Upvotes: 1