combinations of variable length nested lists

xauau xauau at yahoo.com.au
Wed Aug 8 13:24:56 EDT 2001


"Joseph A. Knapka" <jknapka at earthlink.net> writes:

> xauau wrote:
> 
> > It is [a two-liner] in Python too:
> > 
> > def permute(a):
> >     if len(a) == 0: return [[]]
> >     return [[x] + y for x in a[0] for y in permute(a[1:])]
> 
> Wow. So let me make sure I understand: this says:
> 
> >     if len(a) == 0: return [[]]
> 
> If there are no lists in a, return a list containing the
> empty list. Clear enough.
> 
> >     return [
> 
> A list, each of whose elements is
> 
> >	[x] + y
> 
> a list consisting of a single element [x] prepended
> to a list y
> 
> >          for x in a[0]
> 
> where x is a member of the first list in a
> 
> >            for y in permute(a[1:])]
> 
> and y is some permute() of all the other lists in a.

Yep, spot on. I can't improve your description. 

> ... a little non-obvious to the uninitiated.

Absolutely. I'm not very FP literate myself, but this kind of thing is
common in Lisp. Python makes it even easier, but unless you're
familiar with the core concepts it can seem strange. (Judging by the
above analysis, you'll pick it up pretty quickly though).

You might find this useful:

http://gnosis.cx/publish/programming/charming_python_13.txt



More information about the Python-list mailing list