TypeError:“Node”对象不是iterab

2024-04-18 21:35:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我创建了这个节点类,它有一个子节点数组。现在我想遍历这些子对象,以找到所有可能路径中成本/价值之和最小的值。我在应用深度优先搜索策略。但是在我的一个孩子经历了一次交互之后,我得到了一个类型错误,说“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]


Tags: inselfnodechildreturnifdefval
1条回答
网友
1楼 · 发布于 2024-04-18 21:35:18

这条线错了:

nodeleft.children = (Node(4))

它需要:

^{pr2}$

因为您可以在任何表达式周围放置paren,所以Python不能确定是否要用您的版本创建一个tuple。所以你的台词是:

^{3}$

正如我所料你已经看到的,你的代码最终会认为它是在一组节点对象上迭代,但是它实际上是在试图迭代一个节点对象,这是不符合犹太教义的。在

相关问题 更多 >