vary number of loops

colas.francis at gmail.com colas.francis at gmail.com
Wed Apr 16 09:53:39 EDT 2008


On 16 avr, 15:31, nullgr... at gmail.com wrote:
> Hi everyone,
>
> 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?
>
> 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.
>
> Any help is greatly appreciated,
>
> nullgraph

You can try recursion in a more classic manner:

In [283]: def foo(n):
   .....:     def bar(n):
   .....:         my_elts = xrange(2)
   .....:         if n<=0:
   .....:             raise StopIteration
   .....:         elif n<=1:
   .....:             for elt in my_elts:
   .....:                 yield (elt,)
   .....:         else:
   .....:             for elt in my_elts:
   .....:                 for o_elt in bar(n-1):
   .....:                     yield (elt,)+o_elt
   .....:     for elt in bar(n):
   .....:         print elt
   .....:

In [284]: foo(2)
(0, 0)
(0, 1)
(1, 0)
(1, 1)

In [285]: foo(3)
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

In this case, I have an inner function to generate the whole set of
elements and then an outer loop to process them.
Note that you can have the generation of my_elts depend on rank n of
recursion (that is the index of the set in your list).



More information about the Python-list mailing list