Skip to content

Commit 10a200a

Browse files
authored
Merge pull request #153 from ashwek/ms1
Prefix Evaluation - Python
2 parents c17c023 + da50542 commit 10a200a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Output:
3+
4+
Enter a Prefix Equation (space separated) = + 8 ^ 6 2
5+
Symbol | Action | Stack
6+
-----------------------------------
7+
2 | push(2) | 2
8+
6 | push(6) | 2,6
9+
| pop(6) | 2
10+
| pop(2) |
11+
^ | push(2^6) | 64
12+
8 | push(8) | 64,8
13+
| pop(8) | 64
14+
| pop(64) |
15+
+ | push(64+8) | 72
16+
17+
Result = 72
18+
"""
19+
20+
import operator as op
21+
22+
def Solve(Postfix):
23+
Stack = []
24+
Div = lambda x, y: int(x/y) # integer division operation
25+
Opr = {'^':op.pow, '*':op.mul, '/':Div, '+':op.add, '-':op.sub} # operators & their respective operation
26+
27+
# print table header
28+
print('Symbol'.center(8), 'Action'.center(12), 'Stack', sep = " | ")
29+
print('-'*(30+len(Postfix)))
30+
31+
for x in Postfix:
32+
if( x.isdigit() ): # if x in digit
33+
Stack.append(x) # append x to stack
34+
print(x.rjust(8), ('push('+x+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
35+
else:
36+
B = Stack.pop() # pop stack
37+
print("".rjust(8), ('pop('+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
38+
39+
A = Stack.pop() # pop stack
40+
print("".rjust(8), ('pop('+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
41+
42+
Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values poped from stack & push result to stack
43+
print(x.rjust(8), ('push('+A+x+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
44+
45+
return int(Stack[0])
46+
47+
def Convert(Prefix):
48+
Prefix.reverse() # Reverse the Prefix Equation
49+
return Solve(Prefix) # evaluate the reversed Prefix Equation (as a Postfix Equation)
50+
51+
Prefix = input("\n\nEnter a Prefix Equation (space separated) = ").strip().split(' ')
52+
print("\n\tResult = ", Convert(Prefix))

0 commit comments

Comments
 (0)