Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinations with repetition in python, where order MATTERS

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".

like image 243
Alexander Avatar asked Mar 06 '16 03:03

Alexander


People also ask

Does repetition matter in combinations?

Combinations are selections of objects, with or without repetition, order does not matter. The number of k-element combinations of n objects, without repetition is Cn,k = (n k ) = n! k!(

How do you get all possible combinations without repetition in Python?

A. To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.

Do Itertools sort with combinations?

combinations(iterable, r) : It return r-length tuples in sorted order with no repeated elements.


1 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.

like image 117
MutantOctopus Avatar answered Oct 26 '22 00:10

MutantOctopus