Recursion and Generators

Terry Reedy tjreedy at udel.edu
Fri Jul 9 20:17:42 EDT 2004


"Thomas Philips" <tkpmep at hotmail.com> wrote in message
news:b4a8ffb6.0407091153.4f2c1322 at posting.google.com...
> I'm teaching myself Python and never having used recursion and
> generators, created the simple recursive program shown below and
> single stepped through it in IDLE with the debugger turned on to get a
> feel for how recursion and generators worked.

Bold project.  I learned each separately.  The two together are sometimes a
challenge to understand.

> def testRecursion(n):
>     if n == 1:
>         yield [1]
>     else:
>         for result in testRecursion(n-1):
>             yield result + [n]
>
> print list(testRecursion(4))
>
> As I expect, the program keeps calling testRecursion recursively, and
> then backs its way up, yielding a new result each time it exits. All
> well and good so far.
>
> However, it then calls testRecursion recursively a second time (see
> the sequence of calls below), and of course no results are yielded
> this time around.
>
> I'm not sure why it does so. Is it trying to force each genererator to
> "drop off the end" and return a StopIteration? If so, should it not
> discover that it is done with a level as soon as it backs up to the
> next higher level?
>
>
> '__main__'.testRecursion(), line 5: for result in testRecursion(n-1):
> '__main__'.testRecursion(), line 2: if n == 1:
> '__main__'.testRecursion(), line 5: for result in testRecursion(n-1):
> '__main__'.testRecursion(), line 2: if n == 1:
> '__main__'.testRecursion(), line 5: for result in testRecursion(n-1):
> '__main__'.testRecursion(), line 2: if n == 1:
> '__main__'.testRecursion(), line 3: yield[1]
> '__main__'.testRecursion(), line 3: yield result + [n]
> '__main__'.testRecursion(), line 3: yield result + [n]
> '__main__'.testRecursion(), line 3: yield result + [n]
> '__main__'.testRecursion(), line 5: for result in testRecursion(n-1):
> '__main__'.testRecursion(), line 5: for result in testRecursion(n-1):
> '__main__'.testRecursion(), line 5: for result in testRecursion(n-1):

Since the yield result line is line 6, not 3, and definitely after rather
than before the line 5 for loop, I do not understand this output.  Can you
clarify?

Terry J. Reedy






More information about the Python-list mailing list