我想定义一个静态变量 i (通过对该函数的所有递归调用,我只想要一个 i 的副本)。为此,我在类下方但在函数之外声明了“i”。要使用声明的“i”,我在函数定义中使用了关键字“nonlocal i”。(请参阅下面的代码)即使那样,我也收到错误
SyntaxError: no binding for nonlocal 'i' found
^
nonlocal i
Line 9 (Solution.py)
参考下面的代码,我正在尝试解决一个leetcode问题
# 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