I am trying to merge the K-sorted linked lists link. The code runs fine until somehow it calls the function smallest node with ('head', ListNode{val: 0, next: None}) and ('options', [None]). The test case is a list of nodes that look like this: 1->4->5, 1->3->4, 2->6. Please help me find out why is it doing this and how I can fix it, There's clearly something I am missing.
我正在尝试合并K排序链表链接。代码运行得很好,直到它以某种方式调用了带有(‘head’,ListNode{val:0,Next:None})和(‘Options’,[None])的最小节点函数。测试用例是如下所示的节点列表:1->4->5,1->3->4,2->6。请帮助我找出它为什么这样做,以及我如何修复它,很明显我遗漏了一些东西。
Here's my code:
以下是我的代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
temp = ListNode()
def smallest_node(head, options):
if len(options) > 0:
print("head", head)
print("options", options)
lowest = min(options, key=attrgetter('val'))
options.remove(lowest)
print("options here", options)
head.next = lowest
if lowest.next:
options.append(lowest.next)
print("and options here", options)
print("and lowest", lowest)
smallest_node(lowest, options)
smallest_node(temp, lists)
return temp.next
Here's the error
错误是这样的
AttributeError: 'NoneType' object has no attribute 'val'lowest =
min(options, key=attrgetter('val'))Line 21 in smallest_node
(Solution.py)smallest_node(temp, lists)Line 38 in mergeKLists
(Solution.py)ret = Solution().mergeKLists(param_1)Line 59 in _driver
(Solution.py)_driver()Line 69 in <module> (Solution.py)
Here's the print log:
以下是打印日志:
('head', ListNode{val: 4, next: None})('options', [ListNode{val: 6,
next: None}, ListNode{val: 5, next: None}])('options here',
[ListNode{val: 6, next: None}])('and options here', [ListNode{val: 6,
next: None}])('and lowest', ListNode{val: 5, next: None})('head',
ListNode{val: 5, next: None})('options', [ListNode{val: 6, next:
None}])('options here', [])('and options here', [])('and lowest',
ListNode{val: 6, next: None})('head', ListNode{val: 0, next: None})
('options', [None])
I have tried debugging this with print statements and I can not figure out why the function is being called with the mentioned values of head and options.
我试过用print语句调试这个函数,但我不明白为什么要用前面提到的head和Options的值来调用该函数。
更多回答
if you read the comments on that leet code question, there's people remarking that inputs such as [None] - written as "[[]]"
and [(2,None),None,(0,None)] - written as "[[2],[],[0]]"
如果你读了关于列表代码问题的评论,就会有人评论说,像[None]这样的输入--写成“[[]]”和[(2,None),None,(0,None)]-写成“[[2],[],[0]]”
我是一名优秀的程序员,十分优秀!