1

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.)

Aqueous Carlos
  • 445
  • 7
  • 20
rrter123
  • 43
  • 4
  • 1
    `self.left.change` does _not_ recurse. It doesn't call the function – Jean-François Fabre Nov 14 '18 at 15:27
  • 3
    Is this `self.left.change` supposed to be `self.left.change()`? – Silver Nov 14 '18 at 15:27
  • 1
    I'm not sure this question will be of much benefit for future readers. Maybe OP may delete it ? – kriss Nov 14 '18 at 15:35
  • @rrter123 No, it just means you're human. I once spent more time than I'd like to admit searching for a bug where I had looped on `i` but indexed with `j`. – pjs Nov 14 '18 at 15:35
  • @pjs and in my actual problem I did x instead of self.x. The happy life of the programmer. Do you think I should delete this ask? – rrter123 Nov 14 '18 at 15:43
  • @rrter123 I'm not sure you could delete it at this point, given that there is an upvoted answer. Meanwhile, you got a small bump from it. Even if you can delete it, it's a judgement call on your part. I don't think it's compelling either way. – pjs Nov 14 '18 at 19:40

2 Answers2

1

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

iElden
  • 1,272
  • 1
  • 13
  • 26
0

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

kriss
  • 23,497
  • 17
  • 97
  • 116