Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

k-permutations in lexicographical order

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.

like image 877
georg Avatar asked Dec 01 '11 13:12

georg


2 Answers

You can just use permutations without combinations:

import itertools

a = 'ABCD'
k = 2

for p in itertools.permutations(a, k):
    print "".join(p),

See also:

  • Documentation for permutations(iterable[,r])
like image 93
Sebastian Paaske Tørholm Avatar answered Oct 11 '22 14:10

Sebastian Paaske Tørholm


>>> ["".join(x) for x in itertools.permutations(a, k)]
['AB', 'AC', 'AD', 'BA', 'BC', 'BD', 'CA', 'CB', 'CD', 'DA', 'DB', 'DC']
like image 41
Shawn Chin Avatar answered Oct 11 '22 13:10

Shawn Chin