2017-02-21 50 views
1

我执行的搜索算法(BFS),并具有以下Node类:如何编写__iter__以从叶节点返回到根?

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

回答

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

感谢您的回答。虽然我看到这是如何工作的,但我的具体问题是'__iter__'是否可以用来解决问题?如果不是,我需要了解为什么不。 –

+0

已更新。 '__iter__'本身可以是一个生成器函数。 – schwobaseggl

+0

甜,这是有效的!谢谢! –

相关问题