1

I am writing some recursive function. Consider its prototype to be:

def path(a, row=0, col=0, weight=0, cumulative=[])

I am trying to find some path in the matrix a. The weight adds the values of that path so far and cumulative keeps track of the path.

At some point, this is invoked:

return path(a, row+1, col, weight, cumulative) + path(a, row+1, col+1, weight, cumulative)

Now the base case is as follows:

cumulative.append(a[row][col])
weight = weight + a[row][col]
return weight

which adds the current matrix element into cumulative, adds the weight and returns the weight. The problem is that each time cumulative calls append, it adds to the very same instance of cumulative. How can I ensure that each recursive stack frame takes a different copy of cumulative?

So when append is called in the base case, I want the value of cumulative called to be of the frame caller and not the previous recursive stack frame.

Any suggestions? Thanks.

4
  • cumulative = cumulative[:]? Commented Nov 12, 2012 at 14:27
  • It would be helpful to see your whole function if you don't mind posting :) Commented Nov 12, 2012 at 14:30
  • One thing I'll point out in case you weren't aware. When a default parameter is set to a mutable value such as a list (e.g. cumulative=[]), that value is only initialized once when the function definition is read. That means any time you call path without specifying cumulative, the same list will be used. Commented Nov 12, 2012 at 14:33
  • Thanks Michael - yes I'm aware of that. mux below answered it. I needed a separate instance of cumulative for each frame. Apparently Python passes by reference (something I'm going to read about now). Commented Nov 12, 2012 at 14:34

1 Answer 1

1

you could call with a copy of cumulative:

return path(a, row+1, col, weight, list(cumulative)) + 
       path(a, row+1, col+1, weight, list(cumulative))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.