Search code examples
pythoncombinationspython-itertools

Stuck in python combinations using itertools


I'm using the itertools module in python. I found that combinations_with_replacement does not give me all the combinations.

>>>import itertools
>>>[list(x) for x in itertools.combinations_with_replacement('AB', 3)]
[['A', 'A', 'A'], ['A', 'A', 'B'], ['A', 'B', 'B'], ['B', 'B', 'B']]

It does not give me ['A','B','A'] nor ['B','A','B'].

Does anyone know why is this and, more importantly, how to correct it?


Solution

  • Try product with 3 repeats:

    import itertools
    print [list(x) for x in itertools.product('AB', repeat=3)]
    

    Gives:

    [['A', 'A', 'A'], ['A', 'A', 'B'], ['A', 'B', 'A'], ['A', 'B', 'B'], ['B', 'A', 'A'], ['B', 'A', 'B'], ['B', 'B', 'A'], ['B', 'B', 'B']]

    Remember that using list comprehension you can always resort to:

    ab_str = "AB"
    # don't have to use +, can do (x, y, z,)
    print [x + y + z for x in ab_str for y in ab_str for z in ab_str]
    

    Gives:

    ['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']