[Python][迭代器和生成器] 迭代协议

深度优先的生成器实现

Node Class的创建

class Node:
    def __init__(self, value):
        self._value = value
        self._children = []

    def __repr__(self):
        return 'Node({!r}) '.format(self._value)

    def add_child(self, node):
        self._children.append(node)

    def __iter__(self):
        return iter(self._children)

    def depth_first(self):
        yield self#生成了一个可迭代对象,这个可迭代对象中的元素也具有生成器特性,即也存在depth_first函数
        for c in self:
            yield from c.depth_first()#该实现方法最精妙的地方在于此处。
            						#首先这个self是一个被实例化的对象,depth_first函数本身也实现了生成器的功能
            						

对Node类中的深度优先的测试

if __name__ == '__main__':
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    root.add_child(child1)
    root.add_child(child2)
    child1.add_child(Node(3))
    child1.add_child(Node(4))
    child2.add_child(Node(5))

    for ch in root.depth_first():#从root开始进行深度优先排列
        print(ch)

'''
            node0
            /   \
        node1   node2
        /   \        \
    node3   node4     node5
'''

测试结果

符合深度优先的排列顺序
在这里插入图片描述

普通深度优先的实现

更加普通确更繁琐的解决方法

class DepthFisrtIterator(object):
    def __init__(self, start_node):
        self._node = start_node
        self._children_iter = None
        self._chile_iter = None

    def __iter__(self):
        return self

    def __next__(self):
        if self._children_iter is None:
            self._children_iter = iter(self._node)
            return self._node
        elif self._child_iter:
            try:
                nextchild = next(self._children_iter)
                return nextchild
            except StopIteration:
                self._chile_iter = None
                return next(self)
        else:
            self._children_iter = next(self._children_iter).depth_first()
            return next(self)

猜你喜欢

转载自blog.csdn.net/qq_33868661/article/details/114662383