问题描述
我想定义一个静态变量 i(通过对该函数的所有递归调用,我只需要 i 的一个副本)。为此,我在类下方但在函数之外声明了“i”。要使用声明的“i”,我在函数定义中使用了关键字“nonlocal i”。(请参阅下面的代码)即使如此,我还是收到了错误
SyntaxError: no binding for nonlocal 'i' found
^
nonlocal i
Line 9 (Solution.py)
# 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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)