Module dalpy.stacks
This module holds classes related to LIFO stacks.
This module contains Stack
, an implementation of a LIFO stack, and StackUnderflowError
, an error raised by Stack
.
Examples
Initializing, adding, and removing elements from a Stack
:
s = Stack()
s.push(1)
s.push(2)
s.pop()
The following code will raise a StackUnderflowError
because the second pop is done on an empty Stack
:
s.pop()
s.pop()
Classes
class Stack
-
This class represents a LIFO stack that has no maximum capacity.
Examples
To initialize a
Stack
:s = Stack()
To add elements to the end of
s
:s.push(1) s.push(2)
To remove and return the element at the top of
s
(in this casex = 2
):x = s.pop()
To see the element at the top of
s
(in this casey = 1
):y = s.top()
Initializes an empty
Stack
inO(1)
time.Methods
def is_empty(self)
def pop(self)
-
Removes the element at the top of this
Stack
.This operation runs in
O(1)
time with respect to the size of thisStack
.Returns
The element at the top of the
Stack
that was removed. That is, the element that was last added to thisStack
of the elements in it.Raises
StackUnderflowError
- If this
Stack
is empty.
def push(self, value)
def size(self)
def top(self)
class StackUnderflowError (operation)
-
This class is used by
Stack
to raise errors for operations done on an emptyStack
.Initializes a
StackUnderflowError
that will be raised associated with a particularStack
operation.Args
operation
- a string specifying the operation to raise an error on
Ancestors
- builtins.Exception
- builtins.BaseException