Search code examples
pythoncombinationspython-itertools

Getting all combinations from a list using itertools


I am working on a problem with project Euler and I need to get all combinations of adding int elements in a list,

from itertools import combinations
evenAbs = [12, 18, 20, 24, 30,36]
evenCombs =  sorted(([i+j for i,j in combinations(evenAbs, 2)]))

my problem is that I need the combinations to include 12+12 18+18 etc.. How can I do this?


Solution

  • Use itertools.combinations_with_replacement:

    >>> import itertools
    >>> list(itertools.combinations_with_replacement([1,2,3], 2))
    [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]