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.
cumulative = cumulative[:]?cumulative=[]), that value is only initialized once when the function definition is read. That means any time you callpathwithout specifyingcumulative, the same list will be used.