Open In App

Priority Queue in Python

Last Updated : 29 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest.

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

  1. An element with high priority is dequeued before an element with low priority.
  2. If two elements have the same priority, they are served according to their order in the queue.
    Various applications of the Priority queue in Computer Science are:
    Job Scheduling algorithms, CPU and Disk Scheduling, managing resources that are shared among different processes, etc.

Key differences between Priority Queue and Queue:

  1. In Queue, the oldest element is dequeued first. While, in Priority Queue, an element based on the highest priority is dequeued.
  2. When elements are popped out of a priority queue the result obtained is either sorted in Increasing order or in Decreasing Order. While, when elements are popped from a simple queue, a FIFO order of data is obtained in the result.

Below is a simple implementation of the priority queue.

Python




# A simple implementation of Priority Queue
# using Queue.
class PriorityQueue(object):
    def __init__(self):
        self.queue = []
 
    def __str__(self):
        return ' '.join([str(i) for i in self.queue])
 
    # for checking if the queue is empty
    def isEmpty(self):
        return len(self.queue) == 0
 
    # for inserting an element in the queue
    def insert(self, data):
        self.queue.append(data)
 
    # for popping an element based on Priority
    def delete(self):
        try:
            max_val = 0
            for i in range(len(self.queue)):
                if self.queue[i] > self.queue[max_val]:
                    max_val = i
            item = self.queue[max_val]
            del self.queue[max_val]
            return item
        except IndexError:
            print()
            exit()
 
if __name__ == '__main__':
    myQueue = PriorityQueue()
    myQueue.insert(12)
    myQueue.insert(1)
    myQueue.insert(14)
    myQueue.insert(7)
    print(myQueue)           
    while not myQueue.isEmpty():
        print(myQueue.delete())


Output:

12 1 14 7
14
12
7
1

Note that the time complexity of delete is O(n) in the above code. A better implementation is to use Binary Heap which is typically used to implement a priority queue. Note that Python provides heapq in the library also.

Time complexity: By using heap data structure to implement Priority Queues
Insert Operation: O(log(n))
Delete Operation: O(log(n))


Similar Reads

Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
What is Priority Queue | Introduction to Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved before elements with lower priority values. In a priority queue, each element has a priority value associated with it. When you add an element to the queue, it is inserted in a position based on its
15+ min read
Priority Queue using Queue and Heapdict module in Python
Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. queue.PriorityQueue(maxsize) It is a constructor for a priority queue. maxsize is the number of eleme
3 min read
Why can't a Priority Queue wrap around like an ordinary Queue?
Priority Queue: A priority queue is a special type of queue in which each element is assigned a priority value. And elements are served based on their priority. This means that elements with higher priority are served first. However, if elements with the same priority occur, they will be served in the order in which they were queued. A priority que
3 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Queue? We use min heap in Dijkstra's Algorithm beca
2 min read
Turn a Queue into a Priority Queue
What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the data item stored first will be accessed first". Decla
9 min read
Why does Queue have front but Priority-queue has top in stl?
Why does the queue have front but the priority queue has top in stl? The main difference between a queue and a priority queue is that a queue follows the FIFO (First-In-First-Out) principle, while a priority queue follows a specific priority order. In other words, the elements in a queue are processed in the order they were added, whereas the eleme
8 min read
Difference between Circular Queue and Priority Queue
Queues are fundamental data structures that are used to store and manage a collection of elements. While both circular queues and priority queues are types of queues, they have distinct characteristics and applications. This article will explore the key differences between circular queues and priority queues. Circular Queue:A Circular Queue is an e
4 min read
Multithreaded Priority Queue in Python
The Queue module is primarily used to manage to process large amounts of data on multiple threads. It supports the creation of a new queue object that can take a distinct number of items. The get() and put() methods are used to add or remove items from a queue respectively. Below is the list of operations that are used to manage Queue: get(): It is
2 min read
Heap and Priority Queue using heapq module in Python
Heaps are widely used tree-like data structures in which the parent nodes satisfy any one of the criteria given below. The value of the parent node in each level is less than or equal to its children's values - min-heap.The value of the parent node in each level higher than or equal to its children's values - max-heap. The heaps are complete binary
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg