Search code examples
pythonindexingundefined

Python undefined variable issue


During python programming, i met an undefined error.

The error is about 'flag' variable and i can use it in the above print sentence without any error.

Why the error occur only for index of array?

If you have any ideas, please share it for me.

Thank you for your interest.

class Solution:
    def rob(self, nums: List[int]) -> int:
        global memo
        
        memo = [[0 for j in range(len(nums))] for i in range(2)]
        flag = 0
        #print("===========================")
        def dp(i : int) -> int:
            global flag
            
            if i >= len(nums):
                #print(i,"return 0")
                return 0

            if i == 1:
                flag = 1
                #print(str(i) + " : " + str(globals), memo)

            if memo[flag][i] is not 0: # <= undefined error occur because of flag
                #print(i,"*",memo)
                return memo[i]
            memo[i] = max(dp(i+1), (dp(i+2) + nums[i]))
            if i is len(nums) - 1 and i is not 0:
                result = nums[i] * flag
                flag = 0
                #print(str(i) + " ! " , result)
                return result
            #print(i,"-",memo)
            return memo[i]
        return max(dp(0), dp(1))
NameError: name 'flag' is not defined. Did you mean: 'flags'?
    if memo[flag][i] is not 0:
Line 21 in dp (Solution.py)
    return max(dp(0), dp(1))
Line 37 in rob (Solution.py)
    ret = Solution().rob(param_1)
Line 57 in _driver (Solution.py)
    _driver()
Line 68 in <module> (Solution.py)
  if i is len(nums) - 1 and i is not 0:
  if memo[flag][i] is not 0:

Solution

  • Well, the problem happens because you have a function inside another function so global key word won't work. There are four scopes in Python: Local, Enclose, Global and Built-in and rob function is in Enclose scope, so what you have to do is change for nonlocal key word as following:

    def dp(i : int) -> int:
        nonlocal flag
    
        if i >= len(nums):
           #print(i,"return 0")
           return 0
    

    BTW using local or nonlocal aren't recommended so try to use in other way.