Priority Queue in Python

Posted by Afsal on 19-Jul-2024

What is a Priority Queue?

A priority queue is a data structure that stores elements along with their priority. Elements with higher priority are processed before those with lower priority. If two elements have the same priority, they are processed according to their order in the queue.

Common use cases

  • Task Scheduling
  • Graph Algorithms
  • Event-Driven Simulations
  • AI and Game Development
  • Network Routing
  • Customer Service Systems
  • Resource Management

Python's heapq module provides a simple way to implement a priority queue. Let's dive into the code

Imagine you are building a task management system where tasks have different priorities. We'll use a priority queue to ensure that tasks are processed in the correct order.

Code

import heapq

priority_queue = []

Pushing task to queue

We'll use the heapq.heappush function to add tasks to the priority queue. Each task will be a tuple where the first element is the priority and the second element is the task description

heapq.heappush(priority_queue, (1, 'Write blog post'))

heapq.heappush(priority_queue, (3, 'Reply to emails'))

heapq.heappush(priority_queue, (2, 'Prepare presentation'))

heapq.heappush(priority_queue, (0, 'Fix critical bug'))

Popping Item from queue

We'll use the heapq.heappop function to process tasks in order of their priority

priority, task = heapq.heappop(priority_queue)

complete code

import heapq

priority_queue = []

heapq.heappush(priority_queue, (1, 'Write blog post'))
heapq.heappush(priority_queue, (3, 'Reply to emails'))
heapq.heappush(priority_queue, (2, 'Prepare presentation'))
heapq.heappush(priority_queue, (0, 'Fix critical bug'))

while priority_queue:
    priority, task = heapq.heappop(priority_queue)
    print(f'Processing task: {task} with priority {priority}')

Output

Processing task: Fix critical bug with priority 0

Processing task: Write blog post with priority 1

Processing task: Prepare presentation with priority 2

Processing task: Reply to emails with priority 3

Here we can see that the order of retrieving is based on the priority of the item.

I hope you have learned something from this post. Please share valuable suggestion with afsal@parseltongue.co.in