Skip to content

Instantly share code, notes, and snippets.

@LucasMagnum
Created October 27, 2018 09:49
Show Gist options
  • Save LucasMagnum/455befc62ff667f93b3977b154844169 to your computer and use it in GitHub Desktop.
Save LucasMagnum/455befc62ff667f93b3977b154844169 to your computer and use it in GitHub Desktop.
Priority Queue - Python
class PriorityQueue:
"""
This priority queue uses a given number as priority order.
The smallest number has the higher priority
"""
def __init__(self):
self.queue = []
def enqueue(self, value: str, priority: int) -> None:
"""Add the value the queue based on its priority"""
self.queue.append((value, priority))
self.queue = reorder_queue(self.queue)
def dequeue(self) -> str:
"""Dequeue the first value from the queue"""
# Swap elements and reorder_queue
firstElement, lastElement = self.queue[0], self.queue[-1]
self.queue[0], self.queue[-1] = lastElement, firstElement
value, priority = self.queue.pop()
self.queue = reorder_queue(self.queue)
return value
def is_empty(self) -> bool:
return len(self.queue) == 0
def peek(self) -> str:
"""Show the first value from the queue"""
return self.queue[0][0]
def reorder_queue(queue):
return sorted(queue, key=lambda v: v[1])
if __name__ == '__main__':
hospital_queue = PriorityQueue()
hospital_queue.enqueue("Victor", 3)
hospital_queue.enqueue("Lucas", 1)
hospital_queue.enqueue("Rafael", 4)
hospital_queue.enqueue("Valentina", 2)
priority_list = []
assert hospital_queue.peek() == "Lucas"
while not hospital_queue.is_empty():
priority_list.append(hospital_queue.dequeue())
# Validate the algorithm checking it is returning the right order
assert priority_list == ["Lucas", "Valentina", "Victor", "Rafael"], priority_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment