Search code examples
pythoncombinationscombinatoricspython-itertools

List All Combinations (Python)


I am trying to output all the combinations of a list with certain constraints:

I need to print all the combinations of length x with domain 1 to y.

For instance, let x=3, and domain y=4. I need to generate all possible combinations of 1 to 4 with 3 members, no repetitions:

[1,2,3]
[2,3,4]
[1,2,4]
[1,3,4]

I know that this should be y choose x but its hard to figure out how to loop to find all the combinations.

Using itertools I know how to generate all combinations of length x of a given list:

import itertools
print list(itertools.combinations([1,2,3],2))

but I am lost as to how I should generate all combinations with a certain domain.


Solution

  • To create a list from 1 to y, use range(1, y+1). With this knowledge, it should be pretty straightforward to take your current itertools knowledge and apply it to the problem:

    import itertools
    print list(itertools.combinations(range(1, y+1), x))
    

    To get each result as a list instead of a tuple, you can use a list comprehension:

    print [list(x) for x in itertools.combinations(range(1, y+1), x)]
    

    Or an alternative using map():

    print map(list, itertools.combinations(range(1, y+1), x))