I want to define a static varaible i (I want only one copy of i through all the recursive calls to that function). For that I've declared 'i' just below the class but outside the function. To use the declared 'i', I have used the keyword 'nonlocal i' inside the function definition.(refer to the code below) Even then, I am getting the error
SyntaxError: no binding for nonlocal 'i' found
^
nonlocal i
Line 9 (Solution.py)
Refer to the code below, I am trying to solve a leetcode problem
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
i = 0
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
nonlocal i
if(head is None or head.next is None):
i+=1
return head
else:
p = self.removeNthFromEnd(head.next,n)
if(i>n):
i=i+1
return head
if(i == n):
head.next = p.next
p.next = None
i=i+1
return head
else:
i = i+1
return head