Kesong Xie Kesong Xie - 15 days ago 5
Python Question

Python - understand the scope of the variable pass to a recursive function

I have a recursive function with an array as the parameter that stores the path as I travel a grid, from (0, 0) to (x, y), and I have to skipped some points that are defined as "unavailable"

I implement my function like this

unAvailablePoint = [(1, 2), (3, 0), (0, 3), (2, 3), (0, 1)]

def steppable(point):
return point not in unAvailablePoint

def travel(x, y, path, visited):
if x >= 0 and y >= 0 and steppable((x, y)):
if (x, y) in visited:
return visited[(x, y)]
success = False
if (x, y) == (0, 0) or travel(x-1, y, path, visited) or travel(x, y-1, path, visited):
path = path + [(x, y)] #the path will remain empty even after the recursive call have done some changes to the path
success = True
visited[(x, y)] = success
return success
return False

path = []
visited = {}
travel(3, 3, path, visited)
print(path) //[]


As I print out the
path
at the end, it seems the
path
is still empty. This is not what I expected as a Python novice. Any suggestion would be helpful

Answer

Try to append to the path and not initialize it every iteration of the recursion:

path.append( (x,y) ) #the path will remain empty even after the recursive call have done some changes to the path

instead of:

path = path + [(x, y)] #the path will remain empty even after the recursive call have done some changes to the path

This way, you are not initialize the list each iteration, so it will not be a local variable to the function.