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 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
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).