I have this code to implement a tree in Python. One of the functions is to find the sum of the values of all nodes below (including itself), but this is not working.
I think the reason is because, once I create a node, I can't go back and access it with Node (name, value) - that would create a new node with that name and value, rather than referring to the one in the tree with that name and value, that has children linked to it.
Therefore, the sum_below function is just returning the value of the node. How I can reference the nodes in the tree:
class Node(object):
def __init__(self, name, value):
self.name = name
self.value = value
self.children = []
def add_child(self, obj):
self.children.append(obj)
def sum_below(self):
if self.children == []:
return self.value
else:
ret = self.value
for child in self.children:
ret += child.sum_below()
return ret
def __str__(self, level = 0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__str__(level+1)
return ret
[Edit] My problem is that once I create a node I can't reference it:
#In [2]:
Node(1,100)
parent = Node(1,100)
child = Node(2, 200)
parent.add_child(child)
#In [5]:
print parent
#Out [5]:
100
200
#In [6]:
print Node(1,100)
#Out [6]:
100
So you see, parent, and Node(1,100) are not referencing the same things.
[EDIT]
#In [5]:
parent.sum_below()
#Out[5]:
300
#In [6]:
Node(1,100).sum_below()
#Out[6]:
100
In the code above, Node(1,100).sum_below() should be equal to parent.sum_below(), because they should be referring to the same node, but they're not.
sum_below. You need to dochild.sum_below().self.childrenis always[]) Showing how you actually test your class would be helpful.parent and Node(1,100) are not referencing the same things) is the real lesson here (as already pointed out by Animesh Kumar): whenever you call the object class (e.g. by writingNode(1, 100)) you are creating a new instance ofNodewhich happens to share the same name and value (and class), but which are not related each other in any other way.