-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathInfixToPostfix.py
46 lines (45 loc) · 1.33 KB
/
InfixToPostfix.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
# infix to postfix
n = int(input())
s = input()
l1 = ['(', ')', '+', '-', '*', '/', '^']
temp = []
result = ''
for i in range(n):
if s[i] in l1:
if temp:
if s[i] == '(':
temp.append(s[i])
elif s[i] == '^':
if temp[-1] in ['(', '+', '-', '*', '/']:
temp.append(s[i])
else:
result += s[i]
elif s[i] == '/' or s[i] == '*':
if temp[-1] in ['(', '+', '-']:
temp.append(s[i])
else:
while temp and temp[-1] in ['^', '*', '/']:
result += temp[-1]
temp.pop()
temp.append(s[i])
elif s[i] in ['+', '-']:
if temp[-1] == '(':
temp.append(s[i])
else:
while temp and temp[-1] in ['^', '+', '-', '*', '/']:
result += temp[-1]
temp.pop()
temp.append(s[i])
else:
while temp[-1] != '(':
result += temp[-1]
temp.pop()
temp.pop()
else:
temp.append(s[i])
else:
result += s[i]
while temp:
result += temp[-1]
temp.pop()
print(result)