Open In App

Priority Queue using Queue and Heapdict module in Python

Priority Queue is an extension of the queue with the following properties.

queue.PriorityQueue(maxsize)

It is a constructor for a priority queue. maxsize is the number of elements which can be inserted into queue, its default value is 0. If the maxsize value is less than or equal to 0, then queue size is infinite. Items are retrieved priority order (lowest first).
Functions-



Note : empty(), full(), qsize() are not reliable as they risk race condition where the queue size might change.

Example:






from queue import PriorityQueue
  
q = PriorityQueue()
  
# insert into queue
q.put((2, 'g'))
q.put((3, 'e'))
q.put((4, 'k'))
q.put((5, 's'))
q.put((1, 'e'))
  
# remove and return 
# lowest priority item
print(q.get())
print(q.get())
  
# check queue size
print('Items in queue :', q.qsize())
  
# check if queue is empty
print('Is queue empty :', q.empty())
  
# check if queue is full
print('Is queue full :', q.full())

Output :

(1, 'e')
(2, 'g')
Items in queue : 3
Is queue empty : False
Is queue full : False

heapdict()

Heapdict implements the MutableMapping ABC, meaning it works pretty much like a regular Python dictionary. It’s designed to be used as a priority queue. Along with functions provided by ordinary dict(), it also has popitem() and peekitem() functions which return the pair with the lowest priority. Unlike heapq module, the HeapDict supports efficiently changing the priority of an existing object (“decrease-key” ). Altering the priority is important for many algorithms such as Dijkstra’s Algorithm and A*.

Functions-

Example:




import heapdict
  
h = heapdict.heapdict()
  
# Adding pairs into heapdict
h['g']= 2
h['e']= 1
h['k']= 3
h['s']= 4
  
print('list of key:value pairs in h:\n'
      list(h.items()))
print('pair with lowest priority:\n',
      h.peekitem())
print('list of keys in h:\n',
      list(h.keys()))
print('list of values in h:\n',
      list(h.values()))
print('remove pair with lowest priority:\n',
      h.popitem())
print('get value for key 5 in h:\n',
      h.get(5, 'Not found'))
  
# clear heapdict h
h.clear()
print(list(h.items()))

Output :

list of key:value pairs in h:
 [('g', 2), ('e', 1), ('k', 3), ('s', 4)]
pair with lowest priority:
 ('e', 1)
list of keys in h:
 ['g', 'e', 'k', 's']
list of values in h:
 [2, 1, 3, 4]
remove pair with lowest priority:
 ('e', 1)
get value for key 5 in h:
 Not found
[]

Article Tags :