# Priority Queue in Python

## Priority Queue in Python

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 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, element based on highest priority is dequeued.
2)When elements are popped out of a priority queue then result obtained in 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 simple implementation of priority queue.

 `# 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` `=` `0` `            ``for` `i ``in` `range``(``len``(``self``.queue)):` `                ``if` `self``.queue[i] > ``self``.queue[``max``]:` `                    ``max` `=` `i` `            ``item ``=` `self``.queue[``max``]` `            ``del` `self``.queue[``max``]` `            ``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.

better implementation is to use Binary Heap which is typically used to implement priority queue. Note that Python provides heapq in library also.

```By using heap datastructure to implement Priority Queues, Time complexity:
Insert Operation: O(log(n))
Delete Operation: O(log(n))
```

Last Updated on October 28, 2021 by admin

## Python – random.sample() functionPython – random.sample() function

Python | random.sample() function sample() is an inbuilt function of random module in Python that returns a particular

## File Objects in PythonFile Objects in Python

File Objects in Python A file object allows us to use, access and manipulate all

## Bar Plot in MatplotlibBar Plot in Matplotlib

Bar Plot in Matplotlib A bar plot or bar chart is a graph that represents

## Convert Floats to Integers in a Pandas DataFrameConvert Floats to Integers in a Pandas DataFrame

Convert Floats to Integers in a Pandas DataFrame Let us see how to convert float

## Python | Pandas Dataframe.rank()Python | Pandas Dataframe.rank()

Pandas Dataframe.rank() Pandas Dataframe.rank() method returns a rank of every respective index of a series

## Create a new column in Pandas DataFrame based on the existing columnsCreate a new column in Pandas DataFrame based on the existing columns

Create a new column in Pandas DataFrame based on the existing columns While working with

## Authentication using Python requestsAuthentication using Python requests

Authentication using Python requests Authentication refers to giving a user permissions to access a particular

## Pandas DataFrame.isinPandas DataFrame.isin

When working with Pandas DataFrames, there are often cases where we need to check if