vary number of loops

Tim Chase python.list at tim.thechases.com
Wed Apr 16 15:53:02 CEST 2008


> 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?

I'm not sure lambda is the tool to use here.  Doable, perhaps, 
but improbable in my book.

> For example, for n=2, I want the function to look something like:
> 
> def foo(2)
>    generate 2 sets of elements A, B
>    # mix elements by:
>    for a_elt in A
>       for b_elt in B
>          form all combinations of them
> 
> If n=3, I want to have 3 sets of elements and mix them up using 3 for
> loops.

You might be ineterested in this thread:

http://mail.python.org/pipermail/python-list/2008-January/473650.html

where various solutions were proposed and their various merits 
evaluated.

-tkc






More information about the Python-list mailing list