parameterized iterator?

jerf at compy.attbi.com jerf at compy.attbi.com
Wed Feb 19 00:29:51 EST 2003


On Tue, 18 Feb 2003 18:00:11 -0800, Fortepianissimo wrote:

 for node in root:
>   <do something to node>

I think what you want is to use the thing returned from the generator
directly:

for node in root.preorder():

     <do something>

That'll work fine. You can then parameterize to your heart's content.

When it comes to tree structures, I generally *don't* implement an
__iter__, because there are any number of reasonable ways to iterate on a
tree: depth-first, breadth-first, backwards for both of those, including
the node you're starting on, not including the node you're starting on,
only iterating on the children of the current node (i.e., not
recursively), and quite a lot more. There's no one "right" answer that
makes sense to "promote" to __iter__, so I don't. Just write several
methods as generators implementing one of the traversals, and that's it.




More information about the Python-list mailing list