Merge pull request #146 from chrismclennon/stack · a3linux/Python@606e696 · GitHub
Skip to content

Commit 606e696

Browse files
authored
Merge pull request TheAlgorithms#146 from chrismclennon/stack
Refactor data_structures.Stacks
2 parents a093f55 + 17e1a92 commit 606e696

6 files changed

Lines changed: 151 additions & 125 deletions

File tree

data_structures/Stacks/Balanced_Parentheses.py

Lines changed: 0 additions & 27 deletions
This file was deleted.

data_structures/Stacks/Infix_To_Postfix_Conversion.py

Lines changed: 0 additions & 48 deletions
This file was deleted.

data_structures/Stacks/Stack.py

Lines changed: 0 additions & 50 deletions
This file was deleted.
Lines changed: 21 additions & 0 deletions
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import string
2+
3+
from Stack import Stack
4+
5+
__author__ = 'Omkar Pathak'
6+
7+
8+
def is_operand(char):
9+
return char in string.ascii_letters or char in string.digits
10+
11+
12+
def precedence(char):
13+
""" Return integer value representing an operator's precedence, or
14+
order of operation.
15+
16+
https://en.wikipedia.org/wiki/Order_of_operations
17+
"""
18+
dictionary = {'+': 1, '-': 1,
19+
'*': 2, '/': 2,
20+
'^': 3}
21+
return dictionary.get(char, -1)
22+
23+
24+
def infix_to_postfix(expression):
25+
""" Convert infix notation to postfix notation using the Shunting-yard
26+
algorithm.
27+
28+
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
29+
https://en.wikipedia.org/wiki/Infix_notation
30+
https://en.wikipedia.org/wiki/Reverse_Polish_notation
31+
"""
32+
stack = Stack(len(expression))
33+
postfix = []
34+
for char in expression:
35+
if is_operand(char):
36+
postfix.append(char)
37+
elif char not in {'(', ')'}:
38+
while (not stack.is_empty()
39+
and precedence(char) <= precedence(stack.peek())):
40+
postfix.append(stack.pop())
41+
stack.push(char)
42+
elif char == '(':
43+
stack.push(char)
44+
elif char == ')':
45+
while not stack.is_empty() and stack.peek() != '(':
46+
postfix.append(stack.pop())
47+
# Pop '(' from stack. If there is no '(', there is a mismatched
48+
# parentheses.
49+
if stack.peek() != '(':
50+
raise ValueError('Mismatched parentheses')
51+
stack.pop()
52+
while not stack.is_empty():
53+
postfix.append(stack.pop())
54+
return ' '.join(postfix)
55+
56+
57+
if __name__ == '__main__':
58+
expression = 'a+b*(c^d-e)^(f+g*h)-i'
59+
60+
print('Infix to Postfix Notation demonstration:\n')
61+
print('Infix notation: ' + expression)
62+
print('Postfix notation: ' + infix_to_postfix(expression))

data_structures/Stacks/stack.py

Lines changed: 68 additions & 0 deletions

0 commit comments

Comments
 (0)