-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack_postfixEvaluation.py
52 lines (40 loc) · 1.15 KB
/
Stack_postfixEvaluation.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
48
49
50
from Stack import Stack
from Stack_infixToPostfix import infixToPostfix
def evaluateFunc(op,op1,op2):
res = 0
if op == '+':
res = op1 + op2
elif op == '-':
res = op1 - op2
elif op == '/':
res = op1 / op2
elif op == '*':
res = op1 * op2
elif op == '^':
res = op1**op2
return res
def postfixEval(postfix_str):
postfix_list = postfix_str.split() #postfix string including spaces
# postfix_list = list(postfix_str) #postfix string without spaces
op_stack = Stack()
op1,op2 = 0,0
for token in postfix_list:
if type_ch(token):
op_stack.push(int(token))
else:
op2 = op_stack.pop()
op1 = op_stack.pop()
op_stack.push(evaluateFunc(token,op1,op2))
return op_stack.pop()
def type_ch(x):
try:
int(x)
return True
except:
return False
s = str(input("Enter your expression with spaces in between characters"))
#x = infixToPostfix("10 + 10 * 5 / ( 26 - 1 )")
#x = infixToPostfix("15 * 3 ^ ( 14 - 12 )")
#print x
x = infixToPostfix(s)
print(postfixEval(x))