Priority Queue
Last updated
Was this helpful?
Last updated
Was this helpful?
An implementation of priority queue is captured here:
Ref:
You want to implement a queue that sorts items by a given priority and always returns the item with the highest priority on each pop operation.
An example on how to use it:
In this recipe, the queue consists of tuples of the form(-priority, index, item)
. _Thepriority
value is negated to get the queue to sort items from highest priority to lowest priority. _This is opposite of the normal heap ordering, which sorts from lowest to highest value.
_The role of theindex
variable is to properly order items with the same priority level. By keeping a constantly increasing index, the items will be sorted according to the order in which they were inserted. _However, the index also serves an important role in making the comparison operations work for items that have the same priority level.
If you make
(priority, item)
tuples, they can be compared as long as the priorities are different. However, if two tuples with equal priorities are compared, the comparison fails as before. For example:
By introducing the extra index and making
(priority, index, item)
tuples, you avoid this problem entirely since no two tuples will ever have the same value for
index
(and Python never bothers to compare the remaining tuple values once the result of comparison can be determined):
The core of this recipe concerns the use of theheapq
module. The functionsheapq.heappush()
andheapq.heappop()
insert and remove items from a list_queue
in a way such that the first item in the list has the smallest priority (as discussed in). Theheappop()
method always returns the “smallest” item, so that is the key to making the queue pop the correct items. Moreover, since the push and pop operations have O(log N) complexity where N is the number of items in the heap, they are fairly efficient even for fairly large values of N.