【问题标题】:How to write __iter__ for to iterate from leaf node back to root?如何编写 __iter__ for 从叶节点迭代回根?
【发布时间】:2017-02-21 17:55:07
【问题描述】:

我正在实现一个搜索算法 (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

有没有更好的方法通过在Node 中创建自定义__iter__ 方法来做到这一点?

【问题讨论】:

    标签: python search tree iterator


    【解决方案1】:

    类似这个生成器函数的东西会起作用:

    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)
        # ....
    

    【讨论】:

    • 感谢您的回答。虽然我看到它是如何工作的,但我的具体问题是 __iter__ 是否可以用来解决问题?如果没有,我需要了解为什么不。
    • 已更新。 __iter__ 本身可以是生成器函数。
    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多