-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.py
More file actions
46 lines (34 loc) · 900 Bytes
/
postfix.py
File metadata and controls
46 lines (34 loc) · 900 Bytes
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
from collections import deque
# Function to evaluate a given postfix expression
def evalPostfix(exp):
# base case
if not exp:
exit(-1)
# create an empty stack
stack = deque()
# traverse the given expression
for ch in exp:
# if the current is an operand, push it into the stack
if ch.isdigit():
stack.append(int(ch))
# if the current is an operator
else:
# remove the top two elements from the stack
x = stack.pop()
y = stack.pop()
# evaluate the expression 'x op y', and push the
# result back to the stack
if ch == '+':
stack.append(y + x)
elif ch == '-':
stack.append(y - x)
elif ch == '*':
stack.append(y * x)
elif ch == '/':
stack.append(y // x)
# At this point, the stack is left with only one element, i.e.,
# expression result
return stack.pop()
if __name__ == '__main__':
exp = '1232*+-8-'
print(evalPostfix(exp))