Python: recursive method rollbacks changes?

Question:

So I got stuck on something like this (a simplified version)

class Node:
    def __init__(self):
        self.left= None
        self.cost = 0

    def change(self):
        if self.left is not None:
            self.left.cost=self.cost+1
            self.left.change

data=[]
for i in range(10):
    data.append(Node())
    if i>0:
        data[i].left = data[i-1]

data[8].change()
print(data[2].cost) #0

I want data[2].cost to have changed, but it rollbacks. Can I make it works without skipping recursion? (In full version I actually keep a two-dimensional array of nodes that have four pointers, so making an iteration suck.)

Asked By: rrter123

||

Answers:

You forgot () when you call your change method.

def change(self):
    if self.left is not None:
        self.left.cost=self.cost+1
        self.left.change()

output:

6

Answered By: iElden

Obviously you want to call change but you didn’t. You just refered to the function object and did nothing with it.

Just change self.left.change to self.left.change() to call it

Answered By: kriss