Can you define several different iterators for a Python class?

I am writing a very simple Tree class:

class Tree:
    def __init__(self, value_ = None, children_ = None):
        self.value = value_
        self.children = children_

I would like to be able to bypass DFS and BFS using a simple loop, that is:

t = Tree()
# ...fill tree...

for node in t:
    print(node.value)

In C ++, for example, you can have several types of iterators - so I could define both a DFS and a BFS iterator and use this or that option depending on what type of workaround I wanted to do. Is this possible to do in Python?

+4
source share
2 answers

, , __iter__. , DFS BFS :

from collections import deque

class Tree(object):
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

    def __iter__(self):
        if self.left:
            for x in self.left:
                yield x

        yield self.value

        if self.right:
            for x in self.right:
                yield x

    def bfs(self):
        q = deque([self])
        while q:
            x = q.popleft()
            if x:
                yield x.value
                q.extend([x.left, x.right])

:

root = Tree(2)
root.left = Tree(1)
root.right = Tree(4)
root.right.left = Tree(3)
root.right.right = Tree(5)

print list(root) # [1, 2, 3, 4, 5]
print list(root.bfs()) # [2, 1, 4, 3, 5]
+7

. , , , . - :

for node in t.depth_first():
    # ...

for node in t.breadth_first():
    # ...
+1

All Articles