osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Permutations using a recursive generator


Hello

I found a smart and very concise code to
generate all permutations of a list.
I put it here if someone is interested to
figure out how it works


def permut(li, prefix=[]):

     if len(li)==1:
         yield prefix + li
     else:
         for elt in li:
             li2 = li.copy()
             li2.remove(elt)
             yield from S(li2, prefix+[elt])


exemple of usage

 >>> list(permut(['a', 'b', 'c']))
[['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], 
['c', 'a', 'b'], ['c', 'b', 'a']]

 >>> list(permut([0,1,2,3]))
[[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], 
[0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], 
[1, 3, 0, 2], [1, 3, 2, 0], [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3], 
[2, 1, 3, 0], [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 0, 2, 1], 
[3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]]