Python/data_structures/stacks/stack.py

69 lines
1.9 KiB
Python
Raw Normal View History

2019-10-05 05:14:13 +00:00
__author__ = "Omkar Pathak"
2018-10-19 12:48:28 +00:00
class Stack:
2018-10-19 12:48:28 +00:00
""" 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)
"""
def __init__(self, limit=10):
self.stack = []
self.limit = limit
def __bool__(self):
return bool(self.stack)
2018-10-19 12:48:28 +00:00
def __str__(self):
return str(self.stack)
def push(self, data):
""" Push an element to the top of the stack."""
if len(self.stack) >= self.limit:
raise StackOverflowError
self.stack.append(data)
def pop(self):
""" Pop an element off of the top of the stack."""
if self.stack:
return self.stack.pop()
else:
2019-10-05 05:14:13 +00:00
raise IndexError("pop from an empty stack")
2018-10-19 12:48:28 +00:00
def peek(self):
""" Peek at the top-most element of the stack."""
if self.stack:
return self.stack[-1]
def is_empty(self):
""" Check if a stack is empty."""
return not bool(self.stack)
def size(self):
""" Return the size of the stack."""
return len(self.stack)
class StackOverflowError(BaseException):
pass
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2018-10-19 12:48:28 +00:00
stack = Stack()
for i in range(10):
stack.push(i)
2019-10-05 05:14:13 +00:00
print("Stack demonstration:\n")
print("Initial stack: " + str(stack))
print("pop(): " + str(stack.pop()))
print("After pop(), the stack is now: " + str(stack))
print("peek(): " + str(stack.peek()))
2018-10-19 12:48:28 +00:00
stack.push(100)
2019-10-05 05:14:13 +00:00
print("After push(100), the stack is now: " + str(stack))
print("is_empty(): " + str(stack.is_empty()))
print("size(): " + str(stack.size()))