Python:NameError:全局名称'sortList'未定义(在递归中)
在这一行(l1 = sortList(head)
)的递归中,我遇到了一个错误:NameError: global name 'sortList' is not defined
。谁能告诉我我哪里出错了?
class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if head == None or head.next == None:
return head
slow = head
fast = head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
fast = slow
slow = slow.next
fast.next = None
l1 = sortList(head)
l2 = sortList(slow)
l = mergeTwoLists(l1, l2)
return l
3 个回答
0
你没有导入任何叫做 sortList
的函数,所以现在只有在 Solution
对象上可以调用的 sortList
。
你可以使用 self.sortList
。这里的 self
是一个在 Python 中用来指代当前对象的变量,类似于其他语言中的 this
。
1
把 l1 = sortList(head)
改成 l1 = self.sortList(head)
,再把 l2 = sortList(slow)
改成 l2 = self.sortList(slow)
。因为 sortList
是在 Solution
这个类里面定义的,而不是全局可用的,所以你需要用 self
来指代当前的 Solution
对象。
9
sortList
是 Solution
这个类里的一个方法,它不能单独存在。
用法如下:
self.sortList(head)
这样就可以正常工作了。