【问题标题】:Python class scope lost in nested recursion functionPython 类范围在嵌套递归函数中丢失
【发布时间】:2021-10-25 19:41:14
【问题描述】:

当我尝试在 python 类中编写递归嵌套函数时,每次递归函数完成并返回到第一个函数时,我的类属性都会恢复到原始状态。

def main():
    input = [
        [1,3,1],
        [1,5,1],
        [4,2,1]
    ]
    sln = Solution()
    sln.findPath(input)
    print("Output: " + str(sln.minPathSum))
    print(*sln.minPath, sep = "->")

class Solution():
    minPath = []
    minPathSum = None
    grid = []

    def findPath(self, grid):
        self.minPath = []
        self.minPathSum = None
        self.grid = grid
        self.recurse(0,0,[])

    def recurse(self, xCoord, yCoord, currentPath):
        if(len(self.grid) <= yCoord):
            return
        if(len(self.grid[yCoord]) <= xCoord):
            return

        currentValue = self.grid[yCoord][xCoord]
        currentPath.append(currentValue)

        if(len(self.grid) - 1 == yCoord and len(self.grid[yCoord]) - 1 == xCoord):
            currentPathSum = sum(currentPath)
            if(self.minPathSum == None or currentPathSum < self.minPathSum):
                self.minPathSum = currentPathSum
                self.minPath = currentPath
        else:
            #right
            self.recurse(xCoord + 1, yCoord, currentPath)
            #down
            self.recurse(xCoord, yCoord + 1, currentPath)

        currentPath.pop()
        return

if __name__ == "__main__":
    main()

运行此结果:

Output: 7

在 VSCode 中调试代码确实表明 self.minPath 正在递归函数中设置;但是,它似乎正在失去原始类实例的范围。

此外,我尝试使用单独的代码重新创建相同的嵌套情况,结果如下。

def main():
    tst = ScopeTest()
    tst.run()
    print(*tst.tstArray)
    print(tst.tstNumber)

class ScopeTest():
    tstArray = []
    tstNumber = 0

    def run(self):
        self.otherFunc()

    def otherFunc(self):
        self.tstArray = [1,2,3,4,5]
        self.tstNumber = 7

if __name__ == "__main__":
    main()

上面确实返回了预期的结果,这让我认为这与递归有关。

提醒一下,我对 python 还很陌生,所以我可能会犯一个新手错误,但我似乎无法弄清楚为什么会这样。

【问题讨论】:

  • 给定一个由非负数填充的 M x N 网格,找到一条从左上角到右下角的路径,该路径最小化沿其路径的所有数字的总和。注意:您只能在任何时间点向下或向右移动。
  • 看我的回答...

标签: python recursion scope


【解决方案1】:

您的recurse() 方法正在生成currentPath 参数,当认为这是正确的时,您执行:self.minPath = currentPath。不幸的是,您只是引用了与 currentPath 相同的对象,后者后来发生了变异。

您的线路应该是:self.minPath = currentPath[:]

然后你会看到self.minPath中的一些内容

必须链接到Ned Batchelder

您也可以删除这些行:

minPath = []
minPathSum = None
grid = []

从正下方class Solution():

【讨论】:

  • 有道理!所以基本上每次我从 currentPath 中弹出一个项目时,我也从self.minPath 中弹出。只需要第二双眼睛。谢谢你的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2015-11-07
  • 2016-06-25
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
相关资源
最近更新 更多