Linear Time Tree Traversal Generator

Chris Angelico rosuav at gmail.com
Tue Sep 20 22:47:18 EDT 2016


On Wed, Sep 21, 2016 at 12:34 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
>     "since values from the leaves of the tree have to be yielded
>     multiple times to the top of the tree"
>
> Each leaf is yielded once, and I don't understand what you mean by yielding
> to the top of the tree.

Ultimately, yes. But AIUI he's talking about this:

def leaf():
    yield 42
def intermediate():
    yield next(leaf())
def root():
    yield next(intermediate())

The value 42 gets "passed up the chain" until it gets to the top. IMO
the cost of that should be dwarfed by the actual work of whatever's
doing the traversal, but it is potentially a cost. And 'yield from',
being a single opcode, is potentially optimizable (and I believe
CPython does optimize long yield-from chains), so there's no good
reason not to use it - more readable AND potentially faster.

ChrisA



More information about the Python-list mailing list