Data Structures

How do you implement a priority queue in Python?

Medium
5
Added
A priority queue is an abstract data type that supports inserting elements with an associated priority and removing the element with the highest priority. You can implement a priority queue using the queue.PriorityQueue class in Python.

Solution Code

Data Structures
import queue

pq = queue.PriorityQueue()

# Example usage
pq.put((2, "code"))
pq.put((1, "eat"))
pq.put((3, "sleep"))

while not pq.empty():
    print(pq.get())
Explanation
This code snippet demonstrates how to implement a priority queue in Python using the queue.PriorityQueue class.

Guided Hints

Import the queue module
Use PriorityQueue to create a priority queue
Use put to add items with priority
Use get to remove items based on priority