Source code for libutilitaspy.data_structures.stacks
"""
This module implements basic stacks. See `<http://en.wikipedia.org/wiki/Stack_(data_structure)>`_
"""
[docs]class EmptyStack(Exception):
"""This exception is used to indicate that a stack is empty when attempting to pop an item."""
pass
[docs]class Stack:
"""
This class implements basic stacks, supporting non-popping iteration over its items.
"""
def __init__(self, elements = []):
self.stack = []
self.top_index = - 1
for item in reversed(elements):
self.push(item)
[docs] def push(self, item):
"""Pushes item to the top of the stack."""
self.stack.append(item)
self.top_index += 1
[docs] def pop(self):
"""Pops and returns the top of the stack.
:returns: The top item in the stack.
:raises EmptyStack: if the stack is empty.
"""
if self.top_index < 0:
raise EmptyStack()
self.top_index -= 1
return self.stack.pop()
[docs] def top(self):
"""Returns the top of the stack without poping it.
:returns: The top item in the stack.
:raises EmptyStack: if the stack is empty.
"""
if self.top_index < 0:
raise EmptyStack()
return self.stack[self.top_index]
[docs] def isempty(self):
""":returns: True if the stack is empty, False otherwise."""
return self.top_index < 0
def __iter__(self):
"""Returns self as an iterator, with the iterator pointer reset to the top of the stack."""
self.iter_index = self.top_index
return self
[docs] def next(self):
"""Obtains the next item in the stack, without removing it.
:raises: StopIteration if the iterator reaches the bottom of the stack."""
if self.iter_index < 0:
raise StopIteration
answer = self.stack[self.iter_index]
self.iter_index -= 1
return answer
def __str__(self):
return str([str(self.stack[i]) for i in range(self.top_index, -1, -1)])