Skip to content

Refactor data_structures.Stacks #146

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 0 additions & 27 deletions data_structures/Stacks/Balanced_Parentheses.py

This file was deleted.

48 changes: 0 additions & 48 deletions data_structures/Stacks/Infix_To_Postfix_Conversion.py

This file was deleted.

50 changes: 0 additions & 50 deletions data_structures/Stacks/Stack.py

This file was deleted.

21 changes: 21 additions & 0 deletions data_structures/Stacks/balanced_parentheses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from Stack import Stack

__author__ = 'Omkar Pathak'


def balanced_parentheses(parentheses):
""" Use a stack to check if a string of parentheses are balanced."""
stack = Stack(len(parentheses))
for parenthesis in parentheses:
if parenthesis == '(':
stack.push(parenthesis)
elif parenthesis == ')':
stack.pop()
return not stack.is_empty()


if __name__ == '__main__':
examples = ['((()))', '((())']
print('Balanced parentheses demonstration:\n')
for example in examples:
print(example + ': ' + str(balanced_parentheses(example)))
62 changes: 62 additions & 0 deletions data_structures/Stacks/infix_to_postfix_conversion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import string

from Stack import Stack

__author__ = 'Omkar Pathak'


def is_operand(char):
return char in string.ascii_letters or char in string.digits


def precedence(char):
""" Return integer value representing an operator's precedence, or
order of operation.

https://en.wikipedia.org/wiki/Order_of_operations
"""
dictionary = {'+': 1, '-': 1,
'*': 2, '/': 2,
'^': 3}
return dictionary.get(char, -1)


def infix_to_postfix(expression):
""" Convert infix notation to postfix notation using the Shunting-yard
algorithm.

https://en.wikipedia.org/wiki/Shunting-yard_algorithm
https://en.wikipedia.org/wiki/Infix_notation
https://en.wikipedia.org/wiki/Reverse_Polish_notation
"""
stack = Stack(len(expression))
postfix = []
for char in expression:
if is_operand(char):
postfix.append(char)
elif char not in {'(', ')'}:
while (not stack.is_empty()
and precedence(char) <= precedence(stack.peek())):
postfix.append(stack.pop())
stack.push(char)
elif char == '(':
stack.push(char)
elif char == ')':
while not stack.is_empty() and stack.peek() != '(':
postfix.append(stack.pop())
# Pop '(' from stack. If there is no '(', there is a mismatched
# parentheses.
if stack.peek() != '(':
raise ValueError('Mismatched parentheses')
stack.pop()
while not stack.is_empty():
postfix.append(stack.pop())
return ' '.join(postfix)


if __name__ == '__main__':
expression = 'a+b*(c^d-e)^(f+g*h)-i'

print('Infix to Postfix Notation demonstration:\n')
print('Infix notation: ' + expression)
print('Postfix notation: ' + infix_to_postfix(expression))
68 changes: 68 additions & 0 deletions data_structures/Stacks/stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
__author__ = 'Omkar Pathak'


class Stack(object):
""" 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 not bool(self.stack)

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:
raise IndexError('pop from an empty stack')

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


if __name__ == '__main__':
stack = Stack()
for i in range(10):
stack.push(i)

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()))
stack.push(100)
print('After push(100), the stack is now: ' + str(stack))
print('is_empty(): ' + str(stack.is_empty()))
print('size(): ' + str(stack.size()))