combinations of variable length nested lists

Alex Martelli aleax at aleax.it
Wed Aug 8 08:04:30 EDT 2001


"xauau" <xauau at yahoo.com.au> wrote in message
news:840bdd8f.0108080216.6dffdbc9 at posting.google.com...
    ...
> def permute(a):
>     if len(a) == 0: return [[]]
>     return [[x] + y for x in a[0] for y in permute(a[1:])]
>
> Actually, it needs all of three lines if you count the func def ;-)
>
> Just for fun, does anyone know how to move the 'if' into the list
> comprehension to make it a one-liner?

It's easy to oneline this function's body _without_ moving
the test inside the list comprehension (it's a long line
so my newsreader might break it, but it's logically one):

return (len(a)==0 and [[]]) or [[x]+y for x in a[0] for y in permute(a[1:])]


Alex






More information about the Python-list mailing list