Skip to content
Pritam Kundu edited this page Aug 3, 2023 · 6 revisions

Introduction

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

Usage

from datastax.Arrays import Stack

1.1 Method signatures and Class Hierarchy

class Stack(AbstractStack):
    def __init__(self, *, capacity: Optional[int] = sys.maxsize) -> None: ...
    def is_full(self) -> bool: ...
    def is_empty(self) -> bool: ...
    def push(self, item: Any) -> int: ...
    def pop(self) -> Any: ...
    def peek(self) -> Any: ...

1.2 Constructor

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

1.3 is_full

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

1.4 is_empty

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

1.5 push

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

1.6 pop

  • Takes no arguments and removes 1 item from the top of the stack.
  • Returns the item of successful pop operation.
  • Raises UnderflowError if stack is found empty.
s = Stack() 
s.push(10) 
s.pop() # 10 ✅
s.pop() # ❌ UnderflowError: Stack is already empty, can't perform POP ...

1.7 peek

  • Takes no arguments and returns the item from the top of the stack.
  • returns STACK EMPTY if stack is found empty
s = Stack() 
s.push(10)
s.peek() # 10 

---

s.pop()
s.peek() # 'STACK EMPTY'