我正在实施搜索算法(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
方法,有更好的方法吗?
答案 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)
# ....