Search code examples
pythonrecursionnameerror

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


I have a recursive function which computes some answer at the end and I have to store the maximum of these temporary answers and return it.

The code is as follows.
(If you know this, I am not worried about Kadane's Algorithm, I wanted to know how to get this done)

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

The error I get is: NameError: name 'ans' is not defined

How do I store the maximum value and return it in such cases? Since this doesn't work.


Solution

  • This is the perfect use case for the nonlocal keyword! This keyword allows you to refer to the ans variable in the enclosing function.

    Solution (simply replace global with 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