【问题标题】:variable not defined even after setting as global (Python) + How do I approach such cases?即使设置为全局(Python)后变量也没有定义+我该如何处理这种情况?
【发布时间】:2021-01-20 14:10:33
【问题描述】:

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

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

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

在这种情况下如何存储最大值并返回?因为这不起作用。

【问题讨论】:

  • 因为第一次尝试使用时没有全局ans

标签: python recursion nameerror


【解决方案1】:

这是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

【讨论】:

  • "此关键字允许您在封闭函数中引用 ans 变量。"它允许你assign给它,你总是可以仅仅引用它。但是,是的,这比使用全局变量要好得多
【解决方案2】:

您必须在第一个函数和第二个函数中添加两次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

【讨论】:

    【解决方案3】:

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

    以下代码应该可以工作:

    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,还要在您希望分配给变量的每个函数中输入。

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多