Python2 PriorityQueue和Python3 PriorityQueue的put方法之间有什么区别吗?

时间:2019-09-19 18:03:00

标签: python python-3.x python-2.7

我正在解决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)

有什么想法吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

问题在于__lt__未实现__lt__方法。

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

当您推送到PriorityQueue时,将对其进行排序,并且需要执行angular-gauge-chart@0.7.2方法。