-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix.py
31 lines (29 loc) · 906 Bytes
/
postfix.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
from stack import Stack
def postfix(exp):
precedence = {'+':1, '-':2, '*':3, '/':4}
operand = '0123456789'
result = ''
stk = Stack()
for symbol in exp:
if symbol == '(':
stk.push(symbol)
elif symbol == ')':
val = stk.pop()
while val != '(':
result += val
val = stk.pop()
elif symbol in operand:
result += symbol
elif symbol in precedence:
if not(stk.isEmpty()):
stkTop = stk.top()
while not(stk.isEmpty()) and stkTop != '(' \
and precedence [stkTop] >= precedence[symbol]:
result += stk.pop()
return result
def main():
exp = input('Enter the expression in infix notation: ')
exp = postfix(exp)
print(exp)
if __name__ == '__main__':
main()