Python pointers to None variables
I have a method that creates a new node in the tree - left or right. If the value is below my current value, it is inserted on the left, otherwise on the right.
I want to refactor this code to first see which side I need to insert my element from and then insert it. Before I did this twice: once for the left side and once for the right side.
It now looks like this:
def neu(self, sortByValue, secondValue):
child = self.left if(sortByValue.lower() < self.value[0].lower()) else self.right
if(child == None):
child = MyTree(sortByValue,secondValue)
else: child.neu(sortByValue,secondValue)
My problem is self.left is None and self.right is None. So when I create the child as a variable and set it to MyTree (...), self.left and self.right don't get a value.
Is there anything I can do to improve this? Thanks!
a source to share
Names are not located in Python variables. For instance:
>>> a = 1
>>> b = a
>>> a = 2
>>> print b
1
In your code, you are just retyping the name child
to a different value (your new node) and does not affect the previously bound value (None).
Here's where you refactor your code to do what you want (untested):
def neu(self, sortByValue, secondValue):
def child(node):
if(node is None):
return MyTree(sortByValue, secondValue)
else:
child.neu(sortByValue, secondValue)
return node
if(sortByValue.lower() < self.value[0].lower()):
self.left = child(self.left)
else:
self.right = child(self.right)
a source to share
Hallo; -)
self.left
or self.right
don't get the value because you are assigning child
, which just keeps a copy of the target value and doesn't reference it.
You want to have a pointer. It doesn't exist directly in Python.
You can express this using a class wrapper, but I find it clearer when you just write both possibilities in an if clause.
a source to share