Combinations with repetition in python, where order MATTERS

Question:

From python’s Documentation: https://docs.python.org/2/library/itertools.html#itertools.combinations

see combinations_with_replacement: “# combinations_with_replacement(‘ABC’, 2) –> AA AB AC BB BC CC”

I’d like to use the same function, with the bonus of generating “BA”, “CA”, and “CB”.

Asked By: Alexander

||

Answers:

itertools.product is definitely the method you’re looking for here. As the documentation states, it is effectively a compact for loop; product(A,B) is equivalent to ((x, y) for x in A for y in B)

product will return every combination of elements that it can, order-specific, so product('ABC', 'DEF', 'GHI') will get you ADG, ADH, ADI, AEG [...] CFI. If you want to include repetition, you set the optional repeat variable. product(A, repeat=4) is equivalent to product(A,A,A,A). Similarly, product(A, B, repeat=3) is the same as product(A,B,A,B,A,B).

In short: to get the result you’re looking for, call itertools.product('ABC', repeat=2). This will get you tuples AA, AB, AC, BA, BB, BC, CA, CB, CC, in order.

Answered By: MutantOctopus