bad generator performance

Alex Martelli aleaxit at yahoo.com
Sun Feb 6 08:47:34 EST 2005


Johannes Ahl-mann <softpro at gmx.net> wrote:

> a non-recursive solution to traversing a recursive data type is bound to
> get ugly, isn't it?

Not necessarily: sometimes using an explicit stack can be quite pretty,
depending.  E.g.:

def all_leaves(root):
    stack = [root]
    while stack:
        rightmost = stack.pop()
        if is_leaf(rightmost):
            yield rightmost
        else:
            stack.extend(rightmost.all_children())

This isn't the traversing you're looking for, but it is _a_ traversing
of a recursive data type, non-recursive, and IMHO quite pretty.


Alex



More information about the Python-list mailing list