-
Notifications
You must be signed in to change notification settings - Fork 1
PriorityQueue
Pritam Kundu edited this page Aug 3, 2023
·
5 revisions
- A priority queue is a strict queue follows FIFO principle with priority incorporated within its items.
- Provides basic functionalities all basic functionalities of queue with special restrictions.
- For additional usage see parent class Queue
from datastax.Arrays import PriorityQueueclass PriorityQueue(Queue):
comparator: Callable
def __init__(self, *, capacity: Optional[int] = sys.maxsize, custom_comparator: Optional[Callable] = max) -> None: ...
def swap(self, index1: int, index2: int) -> None: ...
def heapify(self, index: int, length: int) -> None: ...
def dequeue(self) -> Any: ...
def enqueue(self, item: Any) -> int: ...PriorityQueue(10) # ❌ TypeError: PriorityQueue takes 1 positional argument but 2 were given
PriorityQueue(lambda a, b: a) # ❌ TypeError: PriorityQueue takes 1 positional argument but 2 were given
PriorityQueue() # ✅
PriorityQueue(capacity=10) # ✅
PriorityQueue(custom_comparator=lambda car1, car2: car1 if car1.topSpeed > car2.topSpeed else car2) # ✅
PriorityQueue(capacity=5, custom_comparator=lambda c1, c2: c1 if c1.age > c2.age else c2) # ✅from dataclasses import dataclass
import random
@dataclass
class Person:
age: int
population = 10
ages = list(range(10))
random.shuffle(ages)- Takes 1 argument of any type and inserts it according to its priority
comparator.
pq = PriorityQueue(capacity=population, custom_comparator=lambda p1, p2: p1 if p1.age > p2.age else p2)
for age in ages: pq.enqueue(Person(age))- Takes no arguments and removes 1 item from the according to its priority determined by
comparator.
while not pq.is_empty(): print(pq.dequeue().age, end=', ') # ✅ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
# OR 🧭
while pq: print(pq.dequeue().age, end=', ') # ✅ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, - 1. Home
- 2. Arrays
- 3. Nodes
- 4. Lists
- 5. Trees
- 6. Tables