我有一个递归函数,一个数组作为参数,当我从一个网格行进时存储路径,从(0,0)到(x,y),我必须跳过一些定义为“不可用”的点“
我实现了这样的功能
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) //[]
当我打印出最后的path
时,似乎path
仍为空。这不是我期望的Python新手。任何建议都会有所帮助
答案 0 :(得分:3)
尝试追加到路径,并且不会在每次递归迭代时初始化它:
path.append( (x,y) ) #the path will remain empty even after the recursive call have done some changes to the path
而不是:
path = path + [(x, y)] #the path will remain empty even after the recursive call have done some changes to the path
这样,您不会在每次迭代时初始化列表,因此它不会是函数的局部变量。