Permutation Generator

Paul Rubin http
Fri Aug 12 15:56:41 EDT 2005


Talin <talin at acm.org> writes:
> I'm sure I am not the first person to do this, but I wanted to share
> this: a generator which returns all permutations of a list:
> 
> def permute( lst ):
>     if len( lst ) == 1:
>         yield lst
>     else:
>         head = lst[:1]
>         for x in permute( lst[1:] ):
>             yield head + x
>             yield x + head
>     return
> 
> -- Talin

Hmm:

    >>> for p in permute([1,2,3]):
            print p

    [1, 2, 3]
    [2, 3, 1]
    [1, 3, 2]
    [3, 2, 1]

Oops.



More information about the Python-list mailing list