PYTHON

Implementing a Priority Queue (Min-Heap) with `heapq`

Utilize Python's `heapq` module to create and manage an efficient min-priority queue, essential for tasks like scheduling or Dijkstra's algorithm.

import heapq

def create_priority_queue():
    return [] # A list acts as the heap

def add_task(priority_queue, priority, task):
    heapq.heappush(priority_queue, (priority, task))

def get_next_task(priority_queue):
    if priority_queue:
        return heapq.heappop(priority_queue)[1]
    return None

pq = create_priority_queue()
add_task(pq, 3, 'Write documentation')
add_task(pq, 1, 'Fix critical bug')
add_task(pq, 2, 'Deploy feature')

print(f"Next task: {get_next_task(pq)}") # Fix critical bug
print(f"Next task: {get_next_task(pq)}") # Deploy feature
How it works: This snippet shows how to implement a min-priority queue using Python's `heapq` module. The `heapq` functions operate on regular Python lists, treating them as heaps. `heappush` adds an item while maintaining the heap invariant, and `heappop` efficiently retrieves and removes the smallest item (highest priority in a min-heap). This is crucial for applications requiring efficient retrieval of the 'next best' item, such as task scheduling or graph algorithms.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs