prioity queue in python code example

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 queue.priority queue

from queue import PriorityQueue

class PqElement(object):
    def __init__(self, value: int):
        self.val = value

    #Custom Compare Function (less than or equsal)
    def __lt__(self, other):
        """self < obj."""
        return self.val > other.val

    #Print each element function
    def __repr__(self):
        return f'PQE:{self.val}'

#Usage-
pq = PriorityQueue()
pq.put(PqElement(v))       #Add Item      - O(Log(n))
topValue = pq.get()        #Pop top item  - O(1)
topValue = pq.queue[0].val #Get top value - O(1)