Make a generator from a recursive function

J

James Stroud

This was my answer to the thread "new in programing":

def do_something(*args):
print args

def do_deeply(first, depth, lim, doit=True, *args):
if depth < lim:
do_deeply(first+1, depth+1, lim, False, *args)
if first <= depth:
do_deeply(first+1, depth, lim, True, *args + (first,))
elif doit:
do_something(*args)

do_deeply(first=1, depth=3, lim=4)

I thought it was a good answer, but I think better would be a generator. Is
there a straightforward way to make such a function a generator, or does it
require a not using a recursive function? I think "cheating" would be to
generate the list and make an iterable from it.

Note: this is not the same as "cross" from the "N-uples from list of lists" thread.

James
 
A

Alex Martelli

James Stroud said:
This was my answer to the thread "new in programing":

def do_something(*args):
print args

def do_deeply(first, depth, lim, doit=True, *args):
if depth < lim:
do_deeply(first+1, depth+1, lim, False, *args)
if first <= depth:
do_deeply(first+1, depth, lim, True, *args + (first,))
elif doit:
do_something(*args)

do_deeply(first=1, depth=3, lim=4)

I thought it was a good answer, but I think better would be a generator. Is
there a straightforward way to make such a function a generator, or does it

I'm not entirely sure what you mean, but I will guess it's something not
too different from...:

def do_deeply(first, depth, lim, doit=True, *args):
if depth < lim:
for x in do_deeply(first+1, depth+1, lim, False, *args):
yield x
if first <= depth:
for x in do_deeply(first+1, depth, lim, True, *args + (first,)):
yield x
elif doit:
yield args

to be used with

for x in do_deeply(first=1, depth=3, lim=4):
do_something(*x)


Did I guess right...?


Alex
 
J

James Stroud

Alex said:
I'm not entirely sure what you mean, but I will guess it's something not
too different from...:

def do_deeply(first, depth, lim, doit=True, *args):
if depth < lim:
for x in do_deeply(first+1, depth+1, lim, False, *args):
yield x
if first <= depth:
for x in do_deeply(first+1, depth, lim, True, *args + (first,)):
yield x
elif doit:
yield args

to be used with

for x in do_deeply(first=1, depth=3, lim=4):
do_something(*x)


Did I guess right...?


Alex

Yes, that's what I was thinking. Thank you.
 

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

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top