[Tutor] Yield and recursion

Kent Johnson kent37 at tds.net
Sat Jan 10 14:49:10 CET 2009


On Fri, Jan 9, 2009 at 10:15 PM, Justin <fatcat1111 at gmail.com> wrote:

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

You have to explicitly loop over and yield the results of the
recursive calls; there is no automatic machinery or shortcut for this:

def preorder(tree, index, path=[]):
   if index >= len(tree): return
   path = path + [tree[index]]
   yield path
   for path in preorder(tree, left(index), path):
       yield path
   for path in preorder(tree, right(index), path):
      yield path

You may want to yield just the individual path elements, not the full
path, at each step.

Kent


More information about the Tutor mailing list