即使设置为全局变量 (Python) 也未定义变量 + 如何处理此类情况?

variable not defined even after setting as global (Python) + How do I approach such cases?

我有一个递归函数,它在最后计算一些答案,我必须存储这些临时答案的最大值和 return 它。

代码如下
(如果你知道这个,我不担心卡丹的算法,我想知道如何完成这个)

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        
        ans = nums[0]
        
        def helper(n):
            
            global ans

            if(n == 1):
                return nums[0]
            
            temp = max(nums[n-1], nums[n-1]+helper(n-1))
            
            ans = max(ans, temp) ### how do I do this? ###
            
            return temp
        
        helper(len(nums))
        return ans

我得到的错误是: NameError: name 'ans' is not defined

如何存储最大值并 return 在这种情况下?因为这行不通。

您需要在与变量声明本身相同的函数中声明一个全局变量,因为现在您正试图为嵌套函数范围之外的变量设置一个全局变量。

以下代码应该有效:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        
    global ans
    ans = nums[0]
    
    def helper(n):
        
        global ans
        if(n == 1):
            return nums[0]
        
        temp = max(nums[n-1], nums[n-1]+helper(n-1))
        
        ans = max(ans, temp) ### how do I do this? ###
        
        return temp
    
    helper(len(nums))
    return and

请记住,不仅在定义变量时,而且在要分配给变量的每个函数中,都必须放置 global ans

您必须在第一个函数和第二个函数中添加两次 global ans。 使用您的代码:

class Solution:
def maxSubArray(self, nums: List[int]) -> int:

    global ans

    ans = nums[0]
    
    def helper(n):
        
        global ans

        if(n == 1):
            return nums[0]
        
        temp = max(nums[n-1], nums[n-1]+helper(n-1))
        
        ans = max(ans, temp) ### how do I do this? ###
        
        return temp
    
    helper(len(nums))
    return ans

这是 nonlocal 关键字的完美用例! 此关键字允许您在封闭函数中引用 ans 变量。

解决方案(只需将global替换为nonlocal):

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        
        ans = nums[0]
        
        def helper(n):
            
            nonlocal ans

            if(n == 1):
                return nums[0]
            
            temp = max(nums[n-1], nums[n-1]+helper(n-1))
            
            ans = max(ans, temp) ### how do I do this? ###
            
            return temp
        
        helper(len(nums))
        return ans