0

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
                
techtie
  • 11
  • 4
  • It would probably be easier to just define ```i``` as an instance attribute and reference as ```self.i```. ```nonlocal``` is only defined for nested functions, not class attributes. – sj95126 Jul 21 '21 at 15:38
  • You may also want to change your tagging to ```python``` to get a wider audience. – sj95126 Jul 21 '21 at 15:40

1 Answers1

0

Defining i outside a function in a class means it's reference is self.i, not i. Use a classmethod instead:

class Solution:
    i = 0
    
    @classmethod
    def removeNthFromEnd(cls):
        cls.i += 1
        return cls.i

sol = Solution()
sol.removeNthFromEnd()
sol.removeNthFromEnd()

sol_two = Solution()
sol_two.removeNthFromEnd()

>> 3
misantroop
  • 2,276
  • 1
  • 16
  • 24