You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python嵌套函数用global声明变量仍报NameError未定义问题

报错核心原因

该报错和递归调用没有任何关系,根源是作用域关键字使用错误:

  • 代码中的res定义在minOperations方法内部,属于外层嵌套作用域变量,并非模块级全局变量。
  • 嵌套函数ft_helper中使用global res声明,会让Python直接去模块全局作用域查找res变量,但全局作用域从未定义过该变量,因此触发NameError。
可行解决方案

方案1:使用nonlocal关键字(推荐)

nonlocal是Python专门为嵌套函数场景设计的关键字,作用是声明当前变量引用自外层嵌套函数作用域(非全局、非当前函数本地),直接替换原有global关键字即可修复问题,修正后代码如下:

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        res = -1
        
        def ft_helper(nums, x, pl, pr):
            # 替换global为nonlocal,绑定外层minOperations作用域的res
            nonlocal res
            
            if x == 0:
                current_len = pl + pr
                res = current_len if res == -1 else min(current_len, res)
                return 
            # 新增剪枝逻辑:当左右指针重叠/越过、或当前已取长度超过数组总长时直接返回,减少无效递归
            if pl >= len(nums) or pr < 0 or pl + pr > len(nums):
                return
            ft_helper(nums, x - nums[pl], pl + 1, pr)
            ft_helper(nums, x - nums[pr], pl, pr - 1)
        
        ft_helper(nums, x, pl=0, pr=len(nums)-1)
        return res

补充说明:上述递归实现存在大量重复计算,在算法题场景下容易出现超时问题,可替换为「找和为数组总和减x的最长连续子数组」的滑动窗口方案,将时间复杂度优化到O(n)。

方案2:使用可变对象承载结果(兼容旧版Python)

Python 2等没有nonlocal关键字的版本,可以用列表、字典这类可变对象存储结果值,嵌套函数修改可变对象内部元素时不需要做作用域声明,示例代码如下:

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        # 用列表存储结果,列表属于可变对象
        res = [-1]
        
        def ft_helper(nums, x, pl, pr):
            if x == 0:
                current_len = pl + pr
                res[0] = current_len if res[0] == -1 else min(current_len, res[0])
                return 
            if pl >= len(nums) or pr < 0 or pl + pr > len(nums):
                return
            ft_helper(nums, x - nums[pl], pl + 1, pr)
            ft_helper(nums, x - nums[pr], pl, pr - 1)
        
        ft_helper(nums, x, pl=0, pr=len(nums)-1)
        return res[0]

内容的提问来源于stack exchange,提问作者Eldar Tailov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 16:48:27