NameError: name ‘List’ is not defined/TypeError: ‘type’ object is not subscriptable
在解答剑指Offer06时出现了bug提示
部分源代码
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []
class Solution:
def reversePrint(self, head: ListNode) -> list[int]:
return self.reversePrint(head.next) + [head.val] if head else []
错误警告
Traceback (most recent call last):
File *PATH, line 7, in <module>
class Solution:
File *PATH, line 8, in Solution
def reversePrint(self, head: ListNode) -> List[int]:
NameError: name 'List' is not defined
Traceback (most recent call last):
File *PATH, line 7, in <module>
class Solution:
File *PATH, line 8, in Solution
def reversePrint(self, head: ListNode) -> list[int]:
TypeError: 'type' object is not subscriptable
名称错误:未定义名称“List”
TypeError:“type”对象下标不可用
这个错误的原因是LeetCode给出的默认模板问题,如果要自己运行要更改List[int]
->[int]
具体代码如下:
class Solution:
def reversePrint(self, head: ListNode) -> [int]:
return self.reversePrint(head.next) + [head.val] if head else []
完整此题可运行源代码
# 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> [int]:
return self.reversePrint(head.next) + [head.val] if head else []
if __name__ == "__main__":
First = ListNode(1)
Second = ListNode(3)
Third = ListNode(2)
First.next = Second
Second.next = Third
S = Solution()
list = S.reversePrint(First)
print(list)
# 执行用时:148 ms, 在所有 Python3 提交中击败了6.69% 的用户
# 内存消耗:24.2 MB, 在所有 Python3 提交中击败了9.49% 的用户