Skip to content

Queue(Arrays)

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

Introduction

  • A queue is a linear data-structure which follows FIFO principle
  • Provides basic functionalities like enqeue to insert items and dequeue to remove items.
  • Also provides optional functionality like peek used to view item to be dequeued next.
  • Implemented the queue using a python List as an Array in this module to demonstrate how queue implementation works with static arrays.

Usage

from datastax.Arrays import Queue

1.1 Method signatures and Class Hierarchy

class Queue(AbstractQueue):
    def __init__(self, *, capacity: Optional[int] = sys.maxsize) -> None: ...
    def is_full(self) -> bool: ...
    def is_empty(self) -> bool: ...
    def enqueue(self, item: Any) -> int: ...
    def dequeue(self) -> Any: ...
    def peek(self) -> Any: ...

1.2 Constructor

  • Takes optional capacity as a keyword Argument
  • If not passed, the queue has maxsize capacity
Queue(10) # ❌ TypeError: Queue takes 1 positional argument but 2 were given
Queue(capacity=10) # ✅

1.3 is_full

  • Takes no arguments.
  • Returns True if queue is full.
Queue(capacity=0).is_full() # True
Queue(capacity=10).is_full() # False

1.4 is_empty

  • Takes no arguments.
  • Returns True if queue is empty.
Queue(capacity=0).is_empty() # True
Queue(capacity=10).is_empty() # True

1.5 enqueue

  • Takes 1 argument of any type and inserts it in the end of the queue.
  • Returns 0 on successful enqueue operation.
  • Raises OverflowError if queue is found full.
Queue().enqueue(10) # 0 ✅
Queue(capacity=0).enqueue(10) # ❌ OverflowError: Queue is already full, can't perform ENQUEUE ...

1.6 dequeue

  • Takes no arguments and removes 1 item from the beginning of the queue.
  • Returns the item of successful dequeue operation.
  • Raises UnderflowError if queue is found empty.
q = Queue() 
q.enqueue(10) 
q.dequeue() # 10 ✅
q.dequeue() # ❌ UnderflowError: Queue is already empty, can't perform DEQUEUE ...

1.7 peek

  • Takes no arguments and returns the item from the beginning of the queue.
  • returns QUEUE EMPTY if queue is found empty
q = Queue() 
q.enqueue(10)
q.peek() # 10 

---

q.dequeue()
q.peek() # 'QUEUE EMPTY'