I'm trying to generate k-permutations (variations) in lexicographical (alphabetical) order. For example, this code
import itertools
a = list('ABCD')
k = 2
for c in itertools.combinations(a, k):
for p in itertools.permutations(c):
print "".join(p),
prints
AB BA AC CA AD DA BC CB BD DB CD DC
and I'm looking for
AB AC AD BA BC BD CA CB CD DA DB DC
The answer needs to be iterable, so sort
is not an option.
You can just use permutations
without combinations
:
import itertools
a = 'ABCD'
k = 2
for p in itertools.permutations(a, k):
print "".join(p),
permutations(iterable[,r])
>>> ["".join(x) for x in itertools.permutations(a, k)]
['AB', 'AC', 'AD', 'BA', 'BC', 'BD', 'CA', 'CB', 'CD', 'DA', 'DB', 'DC']
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