Example 1: heapq python how to use comparator
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
setattr(ListNode, "__lt__", lambda self, other: self.val <= other.val)
pq = []
for l in lists:
if l:
heapq.heappush(pq, l)
out = ListNode(None)
head = out
while pq:
l = heapq.heappop(pq)
head.next = l
head = head.next
if l and l.next:
heapq.heappush( pq, l.next)
return out.next
Example 2: python heapq
>>> import heapq
>>> heap = []
>>> heapq.heappush(heap, (5, 'write code'))
>>> heapq.heappush(heap, (7, 'release product'))
>>> heapq.heappush(heap, (1, 'write spec'))
>>> heapq.heappush(heap, (3, 'create tests'))
>>> heapq.heappop(heap)
(1, 'write spec')
>>> heapq.nlargest(2,heap)
[(7, 'release product'),(5, 'write code')]
>>> heapq.nsmallest(2,heap)
[(3, 'create tests'),(5, 'write code')]
>>> heap = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapq.heapify(heap)
>>> heap
[0, 1, 2, 6, 3, 5, 4, 7, 8, 9]
>>> def heapsort(iterable):
... h = []
... for value in iterable:
... heappush(h, value)
... return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]