0

我想定义一个静态变量 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
                
4

1 回答 1

0

在类中定义i函数外部意味着它的引用 is self.i, not i。改用类方法:

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
于 2021-12-02T11:34:28.303 回答