Search code examples
pythoncomparatorpriority-queue

priority queue in Python using comparator


Is there any way exists that can do the java queue priority comparator.comparingInt method in Python?

I want the node which has a higher priority come to the front of the queue.

edited: for example:

class node:
  def __init__(self, label, priority):
      self.label = label
      self.priority = priority
  




node1 = node('a', 3)
node2 = node('b',2)
node3 = node('c', 1)
 
nodes in queue comes like this==> (node1,node2,node3)

Solution

  • As Albin states, you'll need to use the heapq module (unless you want to write your own heap implementation from scratch). One very important thing to note is that this library gives only an implementation of a min-heap, rather than a max-heap.

    To write a comparator for a custom object, you'll need to override the __lt__ function (the function that's called when the < operator is used). So your node class would look like this:

    class node:
      nodes = dict()
    
      def __init__(self, label, priority):
          self.label = label
          self.priority = priority
      
      def __lt__(self, other):
          # Note that we've reversed the operands here, since we want a max-heap.
          return other.priority < self.priority
    

    Then, we can make a heap as follows:

    import heapq
    
    heap = []
    
    node1 = node('a', 3)
    node2 = node('b', 2)
    node3 = node('c', 1)
    
    heapq.heappush(heap, node1)
    heapq.heappush(heap, node2)
    heapq.heappush(heap, node3)
    
    # Should print 'a', 'b', 'c' in that order.
    for i in range(3):
        print(heapq.heappop(heap).label)