Skip to content

Instantly share code, notes, and snippets.

@thomasms
Created April 1, 2025 21:00
Show Gist options
  • Save thomasms/cbdd9073c91915bee4b6ddc5d1092b7d to your computer and use it in GitHub Desktop.
Save thomasms/cbdd9073c91915bee4b6ddc5d1092b7d to your computer and use it in GitHub Desktop.
import enum
from typing import Any, Optional
class Priority(enum.Enum):
HIGH = 1
MEDIUM = 2
LOW = 3
class PQueue:
def __init__(self):
self._x = []
def is_empty(self):
return len(self._x) == 0
def size(self):
return len(self._x)
def put(self, obj: Any, priority: Optional[Priority] = Priority.LOW) -> None:
self._x.append((priority.value, obj))
# sort in place according to priority: 1= high, 3=low
self._x.sort(key=lambda x: x[0])
def get(self) -> Any:
# we take the first (highest priority)
if not self.is_empty():
return self._x.pop(0)[1]
return None
def peek(self) -> Any:
# get without removing from queue
if not self.is_empty():
return self._x[0][1]
return None
pq = PQueue()
pq.put(10)
pq.put(2, Priority.HIGH)
pq.put(3, Priority.MEDIUM)
pq.put(5, Priority.LOW)
print(pq.get())
print(pq.get())
print(pq.get())
print(pq.get())
print(pq.get())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment