Skip to content

PriorityQueue

Pritam Kundu edited this page Aug 3, 2023 · 5 revisions

Introduction

  • 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

Usage

from datastax.Arrays import PriorityQueue

1.1 Method signatures and Class Hierarchy

class 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: ...

1.2 Constructor

  • Takes 2 optional keyword Arguments
    • capacity: maxsize(default)
    • custom_comparator: max(default)
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) # ✅

Example: 🏁🚩

from dataclasses import dataclass
import random


@dataclass
class Person:
    age: int


population = 10
ages = list(range(10))
random.shuffle(ages)

1.3 enqueue

  • 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))

1.4 dequeue

  • 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, 

Clone this wiki locally