所以我创建了这个节点类,它有一个子节点数组。现在我想遍历这些子对象,以找到所有可能路径中成本/价值之和最小的值。我在应用深度优先搜索策略。但是在我的一个孩子经历了一次交互之后,我得到了一个类型错误,说“NodeType不能被迭代”
class Node:
def __init__(self, cost):
self.cost= cost
self.children = None
def get(self):
return self.cost
def findMinPath(self):
min_val = 10000
if self.children is None:
return self.cost
for child in self.children:
temp = child.findMinPath()
if temp<min_val:
min_val=temp
return min_val+self.cost
if __name__ =='__main__':
newnode = Node(0)
nodeleft= Node(5)
nodecenter=Node(3)
noderight=Node(6)
newnode.children={nodeleft,nodecenter,noderight}
nodeleft.children=(Node(4))
Nodecenterleft =Node(2)
Nodecenterright = Node(0)
nodecenter.children={Nodecenterleft,Nodecenterright}
Nodecenterleftleft=Node(1)
Nodecenterleft.children ={Nodecenterleftleft}
Nodecenterleftleftright= Node(1)
Nodecenterleftleft.children={Nodecenterleftleftright}
Nodecenterrightleft = Node(10)
Nodecenterright.children={Nodecenterrightleft}
Noderightleft=Node(1)
Noderightright=Node(5)
noderight.children ={Noderightleft,Noderightright}
print (newnode.findMinPath())
堆栈跟踪如下:
Traceback (most recent call last): File "/Users/yashshah/Desktop/Initializer/tree.py", line 45, in print (newnode.findMinPath()) File "/Users/yashshah/Desktop/Initializer/tree.py", line 17, in findMinPath temp = child.findMinPath() File "/Users/yashshah/Desktop/Initializer/tree.py", line 16, in findMinPath for child in self.children: TypeError: 'Node' object is not iterable [Finished in 0.094s]
这条线错了:
它需要:
^{pr2}$因为您可以在任何表达式周围放置paren,所以Python不能确定是否要用您的版本创建一个tuple。所以你的台词是:
^{3}$正如我所料你已经看到的,你的代码最终会认为它是在一组节点对象上迭代,但是它实际上是在试图迭代一个节点对象,这是不符合犹太教义的。在
相关问题 更多 >
编程相关推荐