pythonic way of depth first and breadth first tree iterators

logistix logstx at bellatlantic.net
Sat Mar 16 15:23:16 EST 2002


An iterator can either be implicit or explicit.  If an object in a for
clause isn't an iterator, the interpreter will try to create one by calling
the __iter__ magic method via iter().  That way:

for x in iterclass:
    # do stuff

translates to this behind the scenes.

for x in iter(iterclass):
    # do stuff

You can also explicitly attach iterators via generator methods.

for x in iterclass.depth():
    #pass

for x in iterclass.breadth():
    # pass

will not be translated to  something like "for x in
iter(iterclass.depth()):" because the depth and breadth methods are already
returning iterators.

--
-

"Dave Reed" <dreed at capital.edu> wrote in message
news:mailman.1016242886.1030.python-list at python.org...
>
> We're planning to use Python in our CS1 and CS2 courses next year so
> I'm beginning to think about the issues for these courses.
>
> http://www.python.org/doc/current/lib/typeiter.html states:
>
>   If a container supports different types of iteration, additional
>   methods can be provided to specifically request iterators for those
>   iteration types. (An example of an object supporting multiple forms
>   of iteration would be a tree structure which supports both
>   breadth-first and depth-first traversal.)
>
> I don't quite understand exatly what that is saying - what would be
> the pythonic way of defining/calling separate breadth first and depth
> first iterators for a binary tree class - i.e., is there a way to
> indicate which method to use when you make the call to iter() so that
> I could do something like: for node in tree('depth'):
>
> and
>
> for node in tree('breadth'):
>
> Or is that just implying that I can make a depth first class iterator
> class and breadth first iterator class that both support the
> corresponding next() method and do something like:
>
> d = DepthIter(tree)
> for node in d:
>
> where DepthIter is a class that takes a tree as a parameter to its
> constructor and has a next() method that returns the nodes in a depth
> first manner. And similarly, write a BreadthIter class?
>
> Thanks,
> Dave
>





More information about the Python-list mailing list