How to generate all permutations of a string?

Boris Borcic bborcic at gmail.com
Fri Jun 23 20:16:14 CEST 2006


Another generator solution, based on computing a permutation from its rank 
according to some natural order. Written for strings.

def perms(s) :
     def nth(n,L,k=1) :
         if k>len(L) :
             if n :
                 raise StopIteration
             return ''
         return nth(n/k,L,k+1)+L.pop(n%k)
     for n in xrange(1<<30) :
         yield nth(n,list(s))



More information about the Python-list mailing list