-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfix_to_postfix.py
More file actions
105 lines (94 loc) · 2.5 KB
/
Copy pathinfix_to_postfix.py
File metadata and controls
105 lines (94 loc) · 2.5 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from asyncio.windows_events import NULL
print("program to convert infix to postfix")
op=["+","-","/","*","^"]
priority={'+':1,'-':1,'*':2,'/':2,'^':3}
def create(l):
res=[]
i=0
while(i<len(l)):
if(l[i].isdigit()):
if(i==len(l)-1):
res.append(l[i])
i+=1
elif(i!=len(l)-1):
if(l[i+1].isdigit()):
res.append(l[i]+l[i+1])
i+=2
else:
res.append(l[i])
i+=1
else:
res.append(l[i])
i+=1
return res
def convert(inf):
stk=[]
postfix=[]
for i in inf:
if(i.isdigit() or i.isalpha()):
postfix.append(i)
elif(i=='(' or i=='{' or i=='['):
stk.append(i)
elif(i==')' or i=='}' or i==']'):
if(i==')'):
while(stk[-1]!='('):
postfix.append(stk.pop())
stk.pop()
if(i==']'):
while(stk[-1]!='['):
postfix.append(stk.pop())
stk.pop()
if(i=='}'):
while(stk[-1]!='{'):
postfix.append(stk.pop())
stk.pop()
else:
while stk and stk[-1]!='(' and priority[i]<=priority[stk[-1]]:
postfix.append(stk.pop())
stk.append(i)
while stk!=[]:
postfix.append(stk.pop())
return postfix
def display(exp):
for i in exp:
print(i,end=" ")
def operation(a, b,op):
a=int(a)
b=int(b)
if(op == '+'):
return b+a
elif(op == '-'):
return b-a
elif(op == '*'):
return b*a
elif(op == '/'):
return b/a
elif(op == '^'):
return pow(b,a);
else:
return NULL
def postfix_eval(postfix):
stk=[]
for i in postfix:
if (i.isdigit()):
stk.append(i)
elif(i in op):
a=stk.pop()
b=stk.pop()
sol=operation(a,b,i)
stk.append(sol)
return sol
#main program
val=input("please enter infix expression:")
infix=create(val)
postfix=convert(infix)
print("the infix expression is:")
display(infix)
print("\nthe potfix expression is:")
display(postfix)
print("\nevaluated value is:",postfix_eval(postfix))
infix.reverse()
prefix=convert(infix)
prefix.reverse()
print("\n the perfix expression is:")
display(prefix)