Permutations with Python Generators

Here’s something neat.

I wanted to experiment creating different permutations of a collection of items. (In fact I’m working on some code for laying out shapes on a surface.)
Prototyping in Python to get my ideas straight I came up with this neat generator solution.

def perm(xs) :
    if xs == [] :
        yield []
    for x in xs :
        ys = [y for y in xs if not y==x]
        for p in perm(ys) :
            yield ([x] + p)

Leave a comment