-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostfixEval.py
49 lines (44 loc) · 1.56 KB
/
PostfixEval.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'''
Author: Sai Uday Bhaskar Mudivarty
Program: Postfix Evaluation (Handles only integers)
Process: Expression should have operands and operators seperated by a space ' '
We require stack to solve this problem
1.If input is operand(digit) we simple push them on stack.
2.If the input is operator we pop two operands and do the required
operation (operand2 operator operand1)
Note: Order should be follow operand2 operator operand1
Let say 2 3 -
so we push 2(operand1) then 3(operand2) when -(operator). if we can
have two answers 1 or -1. But correct one is -1 (2 - 3 = -1).
3.Then after solving Push the result into stack.
'''
def performOperation(op1,op,op2):
op1, op2 = int(op1), int(op2)
if op =='+':
return op2+op1
elif op =='-':
return op2-op1
elif op=='*':
return op2*op1
elif op=='/':
return op2/op1
return None
def postfixEval(expression):
try:
operators = set('+-*/')
s = expression.split(' ')
evallist = list()
for i in s:
if i.isdigit():
evallist.append(i)
elif i in operators:
print(evallist)
evallist.append(performOperation(evallist.pop(),i,evallist.pop()))
else:
raise ValueError()
return evallist.pop()
except ValueError:
print("This program only processes expressions with integer values in it")
if __name__ == "__main__":
expression = "2 3 *"
print(postfixEval(expression))