The priority queue is an advanced type of the queue data structure. Instead of dequeuing the oldest element, a priority queue sorts and dequeues elements based on their priorities.
Priority queues are used to handle scheduling problems where some tasks are prioritized over others.
Since the queue.PriorityQueue class needs to maintain the order of its elements, a sorting mechanism is required every time a new element is enqueued.
Python solves this by using a binary heap to implement the priority queue.
For insertion, the priority queue uses the put function in the following way:
p.put(value)
The get command dequeues the highest priority elements from the queue.
from queue import PriorityQueue
q=PriorityQueue()
q.put(4)
q.put(2)
q.put(1)
q.put(5)
while not q.empty():
next_item=q.get()
print(next_item)
Output-
1 2 3 4 5
0 comments:
Post a Comment
Feel free to share your thoughts and suggestion...