我有一个带有数组作为参数的递归函数,该参数存储我从(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新手所期望的。任何建议都会有所帮助 最佳答案
尝试追加到路径,而不是在每次迭代时初始化它:
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
这样,您不必在每次迭代时都初始化列表,因此它不会是函数的局部变量。