社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

UnboundLocalError:在为一个变量赋值之前引用局部变量“x”,而其他变量在Python中工作

Joey Joestar • 3 年前 • 1054 次点击  

为什么在的赋值错误之前引用了局部变量 cur_max 而我可以用 copy_matrix dfs 作用

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        rows, columns = len(matrix), len(matrix[0])
        copy_matrix = {}
        cur_max = 0
        
        def dfs(r, c, prev):
            if (r < 0 or c < 0 or
                r == rows or c == columns or
                matrix[r][c] <= prev):
                return 0
            
            if (r, c) in copy_matrix:
                return copy_matrix[(r, c)]
            
            max_length = 0
            max_length = max(max_length, 1 + dfs(r + 1, c, matrix[r][c]))
            max_length = max(max_length, 1 + dfs(r - 1, c, matrix[r][c]))
            max_length = max(max_length, 1 + dfs(r, c + 1, matrix[r][c]))
            max_length = max(max_length, 1 + dfs(r, c - 1, matrix[r][c]))
            copy_matrix[(r, c)] = max_length
            cur_max = max(cur_max, copy_matrix[(r, c)])
            
            return max_length
        
        for r in range(rows):
            for c in range(columns):
                dfs(r, c, -1)
        
        return max(copy_matrix.values())

这是我得到的

UnboundLocalError: local variable 'cur_max' referenced before assignment
    cur_max = max(cur_max, copy_matrix[(r, c)])
Line 22 in dfs (Solution.py)
    dfs(r, c, -1)
Line 28 in longestIncreasingPath (Solution.py)
    ret = Solution().longestIncreasingPath(param_1)
Line 49 in _driver (Solution.py)
    _driver()
Line 60 in <module> (Solution.py)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132124
 
1054 次点击  
文章 [ 1 ]  |  最新文章 3 年前