Python理解传递给递归函数的变量范围

2024-09-29 01:36:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个递归函数,它的参数是数组,它存储了从(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新手所期望的。任何建议都会有帮助


Tags: orandthepathinfalsereturnif
1条回答
网友
1楼 · 发布于 2024-09-29 01:36:04

尝试附加到路径,而不是每次递归迭代都初始化它:

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

而不是:

^{pr2}$

这样,就不会在每次迭代时初始化列表,因此它不会是函数的局部变量。在

相关问题 更多 >