vary number of loops

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Apr 16 09:44:32 EDT 2008


On Wed, 16 Apr 2008 06:31:04 -0700, nullgraph wrote:

> I'm new to Python and the notion of lambda, and I'm trying to write a
> function that would have a varying number of nested for loops
> depending on parameter n. This just smells like a job for lambda for
> me, but I can't figure out how to do it. Any hint?

That has nothing to do with ``lambda``.  If you don't think "Hey, that's
smells like a job for a function." then it's no job for ``lambda``, which
is just a way to define a function without automatically binding it to a
name like ``def`` does.

One solution to your problem is recursion.  Untested:

def foo(xs):
    if xs:
        for elt in xs[0]:
            for ys in foo(xs[1:]):
                yield [elt] + ys
    else:
        yield []

Called as ``foo([A, B])``.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list