我正在解决leetcode的Merge K Sorted Lists problem

使用Python2的PriorityQueue模块中的Queue的相同算法会为Python3的PriorityQueue模块中的queue引发错误。

Python2版本:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


from Queue import PriorityQueue

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        # Load the first node from every linked list into a priority queue
        prQueue = PriorityQueue()
        for node in lists:
            if node:
                prQueue.put((node.val, node))

        head = ListNode(0)
        curr = head
        while not prQueue.empty():
            val, node = prQueue.get()
            curr.next = node
            curr = curr.next
            if node.next:
                prQueue.put((node.next.val, node.next))

        return head.next


上面的代码工作正常。

Python3版本:

from typing import List
from queue import PriorityQueue

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        # Load the first node from every linked list into a priority queue
        prQueue = PriorityQueue()
        for node in lists:
            if node:
                prQueue.put((node.val, node))

        head = ListNode(0)
        curr = head
        while not prQueue.empty():
            val, node = prQueue.get()
            curr.next = node
            curr = curr.next
            if node.next:
                prQueue.put((node.next.val, node.next))

        return head.next


上面的代码(Python3版本)不起作用,并输出以下错误:

TypeError: '<' not supported between instances of 'ListNode' and 'ListNode'
    heappush(self.queue, item)
Line 227 in _put (/usr/lib/python3.6/queue.py)
    self._put(item)
Line 143 in put (/usr/lib/python3.6/queue.py)
Line 24 in mergeKLists (Solution.py)
Line 58 in _driver (Solution.py)
Line 71 in &lt;module&gt; (Solution.py)


有什么想法吗?
谢谢!

最佳答案

问题在于ListNode没有实现__lt__方法。

这是影响您的python3中的更改。在python2中,这将不是问题,因为内置的cmp函数将用于排序。

当您推送到PriorityQueue时,将对其进行排序,并且需要执行__lt__方法。

关于python - Python2 PriorityQueue和Python3 PriorityQueue的put方法之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58016695/

10-11 07:45