I’ve implemented a priority queue without using the built-in
The implementation is like a queue in addition to the below:
- Element with the highest priority is at the front of the queue
- If an element is not in the queue, it as added after the element containing priority greater than or equal to its priority.
class PriorityQueue: def __init__(self): self.items = () def enqueue(self, element): """ Add data to the queue as per it's given priority. If item is already present then update its priority. """ priority, data = element if len(self.items) == 0: self.items.append((priority, data)) return for item in range(len(self.items)): if data in self.items(item)(1): self.items(item)(0) = priority elif data not in self.items(item)(1): if self.items(item)(0) < priority: self.items.insert(item, (priority, data)) break def dequeue(self): """ Remove the item with the highest priority from the queue and return it. """ return self.items.pop(0) def peek(self): """ Return item in the front of the priority queue. """ return self.items(0) def is_empty(self): """ Return if the priority queue is empty or not. """ return self.items == ()
Would appreciate any suggestions that would improve the implementation