[Tutor] Yield and recursion
Justin
fatcat1111 at gmail.com
Sat Jan 10 04:15:25 CET 2009
Hello, I am new to Python and I'm having trouble with generators. I
have built a tree (and verified that it looks good, and my left() and
right() functions are correct as well), and I am able to traverse it
as I would expect:
def preorder(tree, index, path=[]):
if index >= len(tree): return
path = path + [tree[index]]
print path
preorder(tree, left(index), path)
preorder(tree, right(index), path)
preorder(tree, 0)
This prints out a series of lists, each containing a subtree, as expected. E.g.,
[0]
[1, 2]
[3, 4, 5, 6]
...
However when I attempt to convert preorder() to a generator and
iterate over the results things don't go as planned:
def preorder(tree, index, path=[]):
if index >= len(tree): return
path = path + [tree[index]]
yield path
preorder(tree, left(index), path)
preorder(tree, right(index), path)
for subtree in preorder(tree, 0):
print subtree
This results in only the first list being returned:
[0]
I suspect it has something to do trying to, on the second pass, yield
from a generator that hasn't been created. Does that sound right? If
so, what can I do?
Would somebody please enlighten this poor confused dev? Thank you in advance.
More information about the Tutor
mailing list