Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Memory Error when generating pairs using itertools.combinations

I have an int list with unspecified number. I would like to find the difference between two integers in the list that match a certain value.

from itertools import combinations

#Example of a list
intList = [3, 6, 2, 7, 1]
diffList = [abs(a -b) for a, b in combinations(intList, 2)]

#Given if difference = 2    
print diffList.count(2)

The code snippet worked but when a larger list is given, I am getting MemoryError. Can anyone tell me if there's something wrong with the codes or the error is due to my hardware limitation?

like image 954
Cryssie Avatar asked Feb 19 '26 15:02

Cryssie


1 Answers

Exactly how large is "a larger list"? If len(intList) is n, len(diffList) will be n*(n-1)//2 (the number of combinations of n things taken 2 at a time). This will consume all your memory if n is large enough.

If you only care about the value 2,

print sum(abs(a-b) == 2 for a, b in combinations(intList, 2))

is one way to do it that consumes very little memory regardless of how large intList is. However, it will still take time proportional to the square of len(intList).

like image 120
Tim Peters Avatar answered Feb 22 '26 03:02

Tim Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!