Computing permutations with a recursive generator expression
#!/usr/bin/python2.5
def permute(li):
"""Generate all permutations of a sequence
>>> for i in permute([1,2,3]): print i
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)"""
return ((i,)+j for i in li for j in (permute([k for k in li if k is not i])
if len(li) > 1 else [()] ) )
import doctest
doctest.testmod(verbose=True)
5 comments