vary number of loops

N

nullgraph

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
 
M

Marc 'BlackJack' Rintsch

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
 
T

Tim Chase

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
 
C

colas.francis

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).
 
R

Reedick, Andrew

-----Original Message-----
From: [email protected] [mailto:python-
[email protected]] On Behalf Of Tim Chase
Sent: Wednesday, April 16, 2008 9:53 AM
To: (e-mail address removed)
Cc: (e-mail address removed)
Subject: Re: vary number of loops
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.

I second that. The thread compared building loops on the fly, building
comprehensions nested to arbitrarily levels, recursion (sloooow!), a
slick cookbook recipe using iterators, etc. and provided timings for
each method. Definitely worth bookmarking.



*****

The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA625
 
M

Mensanator

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


There's always the stupid way:

def ooloop6(a, n, perm=True, repl=True):
if (not repl) and (n>len(a)): return
r0 = range(n)
r1 = r0[1:]
if perm and repl: # permutations with
replacement
v = ','.join(['c%s' % i for i in r0])
f = ' '.join(['for c%s in a' % i for i in r0])
e = ''.join(["p = [''.join((",v,")) ",f,"]"])
exec e
return p
if (not perm) and repl: # combinations with
replacement
v = ','.join(['c%s' % i for i in r0])
f = ' '.join(['for c%s in a' % i for i in r0])
i = ' and '.join(['(c%s>=c%s)' % (j,j-1) for j in r1])
e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
exec e
return p
if perm and (not repl): # permutaions without
replacement
v = ','.join(['c%s' % i for i in r0])
f = ' '.join(['for c%s in a' % i for i in r0])
i = ' and '.join([' and '.join(['(c%s!=c%s)' % (j,k) for k in
range(j)]) for j in r1])
e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
exec e
return p
if (not perm) and (not repl): # combinations without
replacement
v = ','.join(['c%s' % i for i in r0])
f = ' '.join(['for c%s in a' % i for i in r0])
i = ' and '.join(['(c%s>c%s)' % (j,j-1) for j in r1])
e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
exec e
print '\n\n',e,'\n\n'
return p

a = 'abcdefghij'
n = 6

# for lotto use Combinations without Replacement
p = ooloop6(a,n,False, False)
##################################################################

Here's the code that gets executed:

## p = [''.join((c0,c1,c2,c3,c4,c5)) for c0 in a
## for c1 in a for c2 in a for c3 in a for c4 in a
## for c5 in a if (c1>c0) and (c2>c1) and (c3>c2)
## and (c4>c3) and (c5>c4)]
 
N

nullgraph

-----Original Message-----
From: [email protected] [mailto:python-
[email protected]] On Behalf Of Tim Chase
Sent: Wednesday, April 16, 2008 9:53 AM
To: (e-mail address removed)
Cc: (e-mail address removed)
Subject: Re: vary number of loops
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:

where various solutions were proposed and their various merits
evaluated.

I second that. The thread compared building loops on the fly, building
comprehensions nested to arbitrarily levels, recursion (sloooow!), a
slick cookbook recipe using iterators, etc. and provided timings for
each method. Definitely worth bookmarking.


Yes, I second that second :) Very nice thread, I'm leaning toward the
"pythonic method" from there, but thanks for all the other solutions
suggested here. Guess I need to go play with lambda more...

nullgraph
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top