Skip to content
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

fixed balanced_parentheses, Added infix-prefix & postfix evaluation #621

Merged
merged 3 commits into from
Mar 1, 2019
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
6 changes: 4 additions & 2 deletions data_structures/stacks/balanced_parentheses.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import print_function
from __future__ import absolute_import
from .Stack import Stack
from stack import Stack

__author__ = 'Omkar Pathak'

Expand All @@ -12,8 +12,10 @@ def balanced_parentheses(parentheses):
if parenthesis == '(':
stack.push(parenthesis)
elif parenthesis == ')':
if stack.is_empty():
return False
stack.pop()
return not stack.is_empty()
return stack.is_empty()


if __name__ == '__main__':
Expand Down
61 changes: 61 additions & 0 deletions data_structures/stacks/infix_to_prefix_conversion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""
Output:

Enter an Infix Equation = a + b ^c
Symbol | Stack | Postfix
----------------------------
c | | c
^ | ^ | c
b | ^ | cb
+ | + | cb^
a | + | cb^a
| | cb^a+

a+b^c (Infix) -> +a^bc (Prefix)
"""

def infix_2_postfix(Infix):
Stack = []
Postfix = []
priority = {'^':3, '*':2, '/':2, '%':2, '+':1, '-':1} # Priority of each operator
print_width = len(Infix) if(len(Infix)>7) else 7

# Print table header for output
print('Symbol'.center(8), 'Stack'.center(print_width), 'Postfix'.center(print_width), sep = " | ")
print('-'*(print_width*3+7))

for x in Infix:
if(x.isalpha() or x.isdigit()): Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix
elif(x == '('): Stack.append(x) # if x is "(" push to Stack
elif(x == ')'): # if x is ")" pop stack until "(" is encountered
while(Stack[-1] != '('):
Postfix.append( Stack.pop() ) #Pop stack & add the content to Postfix
Stack.pop()
else:
if(len(Stack)==0): Stack.append(x) #If stack is empty, push x to stack
else:
while( len(Stack) > 0 and priority[x] <= priority[Stack[-1]]): # while priority of x is not greater than priority of element in the stack
Postfix.append( Stack.pop() ) # pop stack & add to Postfix
Stack.append(x) # push x to stack

print(x.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format

while(len(Stack) > 0): # while stack is not empty
Postfix.append( Stack.pop() ) # pop stack & add to Postfix
print(' '.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format

return "".join(Postfix) # return Postfix as str

def infix_2_prefix(Infix):
Infix = list(Infix[::-1]) # reverse the infix equation

for i in range(len(Infix)):
if(Infix[i] == '('): Infix[i] = ')' # change "(" to ")"
elif(Infix[i] == ')'): Infix[i] = '(' # change ")" to "("

return (infix_2_postfix("".join(Infix)))[::-1] # call infix_2_postfix on Infix, return reverse of Postfix

if __name__ == "__main__":
Infix = input("\nEnter an Infix Equation = ") #Input an Infix equation
Infix = "".join(Infix.split()) #Remove spaces from the input
print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
50 changes: 50 additions & 0 deletions data_structures/stacks/postfix_evaluation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""
Output:

Enter a Postfix Equation (space separated) = 5 6 9 * +
Symbol | Action | Stack
-----------------------------------
5 | push(5) | 5
6 | push(6) | 5,6
9 | push(9) | 5,6,9
| pop(9) | 5,6
| pop(6) | 5
* | push(6*9) | 5,54
| pop(54) | 5
| pop(5) |
+ | push(5+54) | 59

Result = 59
"""

import operator as op

def Solve(Postfix):
Stack = []
Div = lambda x, y: int(x/y) # integer division operation
Opr = {'^':op.pow, '*':op.mul, '/':Div, '+':op.add, '-':op.sub} # operators & their respective operation

# print table header
print('Symbol'.center(8), 'Action'.center(12), 'Stack', sep = " | ")
print('-'*(30+len(Postfix)))

for x in Postfix:
if( x.isdigit() ): # if x in digit
Stack.append(x) # append x to stack
print(x.rjust(8), ('push('+x+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
else:
B = Stack.pop() # pop stack
print("".rjust(8), ('pop('+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format

A = Stack.pop() # pop stack
print("".rjust(8), ('pop('+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format

Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values poped from stack & push result to stack
print(x.rjust(8), ('push('+A+x+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format

return int(Stack[0])


if __name__ == "__main__":
Postfix = input("\n\nEnter a Postfix Equation (space separated) = ").split(' ')
print("\n\tResult = ", Solve(Postfix))