I am playing with a function that takes a coordinate and a matrix as input and returns a new matrix with all of the "above" boxes shifted down one into where the old coordinate used to be. Essentially this is the "popping" stage of candy crush for a single popped box.
I've written the function recursively and somehow it seems to be modifying the global variable m
instead of the local one. I imagine I could probably fix it by changing the function variable to something other than m
, but I was under the impression that Python disallowed this behavior and required the usage of the global
keyword if you want to change global variables from within a function. However this doesn't seem to be the case for my function and I don't know if it's because of recursion or something else I've missed.
def pop(x,y, m):
"""
while still in bounds,
shift m[x][y-1] to m[x][y]
when m[x][y-1] doesn't exist, replace m[x][y] with 0
"""
if y == 0: #hit end, fill with 0
m[y][x] = 0
return m
else:
m[y][x] = m[y-1][x]
return pop(x, y-1 , m)
m = [[1,2,3,4],
[1,3,4,2],
[4,1,2,4],
[1,2,3,1]]
Now a = pop(2,2, m)
returns the correct value for a
and then checking the value of m
surprisingly also gives:
m= [[1, 2, 0, 4],
[1, 3, 3, 2],
[4, 1, 4, 4],
[1, 2, 3, 1]]