如何编写__iter__来从叶节点迭代回root?

时间:2017-02-21 17:55:07

标签: python search tree iterator

我正在实施搜索算法(BFS)并拥有以下Node类:

class Node:
    def __init__(self, state=None, action=None, path_cost=None, parent=None):
        self._state = state
        self._action = action
        self._path_cost = path_cost
        self._parent = parent

我的BFS解算器返回解决方案节点(子)。有了这个节点,我可以,例如,如下计算总路径成本(此代码是另一个Summary类的一部分):

    def path_cost(self):
        self._cost = self._node.path_cost
        node = self._node.parent
        while node:
            self._cost += node.path_cost
            node = node.parent

        return self._cost

通过在__iter__中创建自定义Node方法,有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

像这个生成器函数的东西可以工作:

class Node:
    def __iter__(self):
        node = self
        while node:
            yield node
            node = node._parent

# elsewhere
cost = sum(n.path_cost for n in self._node)
    # ....