views:

148

answers:

3

Hi everybody!

I have a method that creates a new node in a tree - either left or right. If the value is lower than my current value it is inserted on the left, otherwise on the right side.

I want to refactor this code, so that I first see on which side I have to insert my element, and then insert it. Before I implemented this twice: Once for the left side and once for the right side.

It currently 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, though, that self.left is None, and self.right is None. So when I create child as a variable and set it to MyTree(...), self.left and self.right are not receiving the value.

Is there anything I can do to improve this? Thanks!

+2  A: 

In Python variables are names not locations. For example:

>>> a = 1
>>> b = a
>>> a = 2
>>> print b
1

In your code you're simply rebinding the name child to a different value (your new node) and that has no affect on the previously bound value (None).

Here's a reworking of your code that should 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)
Benji York
A: 

Hallo ;-)

self.left or self.right don't receive the value because you assign to child which just holds a copy of the destination value and no reference to it.

You want to have a pointer- This doesn't exist directly in Python.

You could express this using a class wrapper, but I think it's more comprehensible when you just write both possibilities in the if clause.

Dario
If I wrote both cases in the if clause I would have a repetition of code in that method. This is not very good coding practice, since I would have to maintain practically the same code two times.
Sebastian Hoitz
A: 

Why are you using a tree?

I would use a dictionary:

Initialization:

tree = {}

Adding new node:

tree[sortByValue] = secondValue

Extracting things

print tree[sortByValue]

Not the straight answer but a more pythonic way of doing it

Mr Shark
Well, it is from an assignment in IT class. We have a whole phonebook which consists of many instances of a particular class. Each class has two properties: left and right, where you can store another instance of that class. That way we can build and sort this phone book by the peoples names, for example, when adding an item.
Sebastian Hoitz