Merging K Sorted Lists Using Heapq Module In Python3
Solution 1:
When tuples are compared, their first elements are compared, and then any ties are broken using their second elements, their elements, and so on. For example, (2, "a") < (2, "b")
will evaluate to True
.
Here, you are inserting (node.val, node)
tuples into your heap, which attempts to compare them. If there is a tie on the node value, it moves on to the second element of the tuples - the nodes themselves. These are just ListNode
instances. Python does not know how to compare two ListNodes
, hence the error.
To enable comparisons between ListNodes
, you need to implement the rich comparison methods.
A quick way to do it is to simply implement ListNode.__lt__
and then use the functools.total_ordering
decorator:
import heapq
from functools import total_ordering
@total_orderingclassListNode:def__init__(self, value: float, label: str) -> None:self.value = value
self.label = label
def__lt__(self, other:'ListNode'):
returnself.value <= other.value
def__str__(self):
return f"ListNode(label={self.label}, value={self.value})"
nodes = []
a = ListNode(5, "A")
b = ListNode(3, "B")
c = ListNode(5, "C")
heapq.heappush(nodes, a)
heapq.heappush(nodes, b)
heapq.heappush(nodes, c)
whilenodes:
x = heapq.heappop(nodes)
print(x)
Here we say that comparing two ListNode
objects is the same as just comparing their values. With comparisons defined, you don't even need to insert tuples at all. You can just insert ListNode
objects directly, and rely on the comparison methods.
Solution 2:
I think you are talking about this: Leetcode Merge k Sorted Lists
I am sharing a working solution for you:
head = curr = ListNode(0) # Creating a dummy node
lst = []
for l in lists:
if l:
# Here we need to first push val so that heap can know which is minimum and which is maximum. # If we insert directly node then heap can't work proper way (in this case heapq.heappop doesn't return minimum node).
lst.append((l.val,l))
heapq.heapify(lst)
while lst:
val,node = heapq.heappop(lst)
curr.next = node
curr = curr.next
node = node.nextif node:
heapq.heappush(lst,(node.val,node))
return head.next
Post a Comment for "Merging K Sorted Lists Using Heapq Module In Python3"