As Kevin mention in the comments, your algorithm might be wrong, but anyway your code is not optimized.
When using very big lists, it is common to use generators
, there is a famous, great Stackoverflow answer explaining the concepts of yield
and generator
- What does the "yield" keyword do in Python?
The problem is that your pairs = combinations(anums, 2)
doesn't generate a generator
, but generates a large object which is much more memory consuming.
I changed your code to have this function, since you iterating over the collection only once, you can lazy evaluate the values:
def generator_sol(anums1, s):
for comb in itertools.combinations(anums1, s):
yield comb
Now instead of pairs = combinations(anums, 2)
which generates a large object.
Use:
pairs = generator_sol(anums, 2)
Then, instead of using the lambda
I would use another generator
:
sums_sol = (x[0]+x[1] for x in pairs)
Another tip, you better look at xrange which is more suitable, it doens't generate a list but an xrange object
which is more efficient in many cases (such as here).