data_structures.stacks.stack

Attributes

T

Exceptions

StackOverflowError

Common base class for all exceptions

StackUnderflowError

Common base class for all exceptions

Classes

Stack

A stack is an abstract data type that serves as a collection of

Functions

test_stack(→ None)

Module Contents

exception data_structures.stacks.stack.StackOverflowError

Bases: BaseException

Common base class for all exceptions

exception data_structures.stacks.stack.StackUnderflowError

Bases: BaseException

Common base class for all exceptions

class data_structures.stacks.stack.Stack(limit: int = 10)

Bases: Generic[T]

A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last In, First Out (LIFO). https://en.wikipedia.org/wiki/Stack_(abstract_data_type)

__bool__() bool
__contains__(item: T) bool

Check if item is in stack

>>> S = Stack(3)
>>> S.push(10)
>>> 10 in S
True
>>> S = Stack(3)
>>> S.push(10)
>>> 20 in S
False
__str__() str
is_empty() bool

Check if a stack is empty.

>>> S = Stack()
>>> S.is_empty()
True
>>> S = Stack()
>>> S.push(10)
>>> S.is_empty()
False
is_full() bool
>>> S = Stack()
>>> S.is_full()
False
>>> S = Stack(1)
>>> S.push(10)
>>> S.is_full()
True
peek() T

Peek at the top-most element of the stack.

>>> S = Stack()
>>> S.push(-5)
>>> S.push(10)
>>> S.peek()
10
>>> Stack().peek()
Traceback (most recent call last):
    ...
data_structures.stacks.stack.StackUnderflowError
pop() T

Pop an element off of the top of the stack.

>>> S = Stack()
>>> S.push(-5)
>>> S.push(10)
>>> S.pop()
10
>>> Stack().pop()
Traceback (most recent call last):
    ...
data_structures.stacks.stack.StackUnderflowError
push(data: T) None

Push an element to the top of the stack.

>>> S = Stack(2) # stack size = 2
>>> S.push(10)
>>> S.push(20)
>>> print(S)
[10, 20]
>>> S = Stack(1) # stack size = 1
>>> S.push(10)
>>> S.push(20)
Traceback (most recent call last):
...
data_structures.stacks.stack.StackOverflowError
size() int

Return the size of the stack.

>>> S = Stack(3)
>>> S.size()
0
>>> S = Stack(3)
>>> S.push(10)
>>> S.size()
1
>>> S = Stack(3)
>>> S.push(10)
>>> S.push(20)
>>> S.size()
2
limit
stack: list[T] = []
data_structures.stacks.stack.test_stack() None
>>> test_stack()
data_structures.stacks.stack.T