0

When I'm trying to use res variable in my ft_helper function it gives me error Name is not defined. As you could see I do tell that res variable is global. How do I do in python that variable is available and could be changed in nested functions. More clear in a picturemore clear here in a picture is it because of recursion ?? code:

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        res = -1
        
        def ft_helper(nums, x, pl, pr):
            global res
            
            if x == 0:
                res = pl + pr if res == -1 else  min(pl + pr, res) //error, res name is not defined
                return 
            if(pl >= len(nums) or pr < 0): return
            ft_helper(nums, x = x - nums[pl], pl = pl + 1, pr = pr)
            ft_helper(nums, x = x - nums[pr], pl = pl, pr = pr - 1)
        ft_helper(nums, x, pl = 0, pr = len(nums) - 1)
        return res
1
  • 6
    global should be nonlocal. It's not a global variable, it's a local variable in the minOperations function. Commented Jun 13, 2022 at 17:18

1 Answer 1

2

The solution is simply to replace global res with nonlocal res.

The variable res is not a global variable as it's defined within the scope of minOperations. It is not a local variable (from ft_helper's point-of-view) as it's not defined within ft_helper's scope. Instead it is considered a nonlocal variable from ft_helper's point-of-view.

It you look at PEP 3104, you will see that nonlocal was proposed precisely for situations like yours (accessing non-global variables from outer scopes).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.