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".
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!(
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.
combinations(iterable, r) : It return r-length tuples in sorted order with no repeated elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With