So I created this node class which has an array of children nodes. Now I want to iterate through the children to find the least cost/value total of all the possible paths. I'm applying the depth first search strategy. But after one of my children has undergone an interation, I get a TypeError saying that "NodeType cannot be iterated"
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())
The stack trace is as follows:
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]