-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix conversion.py
More file actions
109 lines (97 loc) · 3.81 KB
/
postfix conversion.py
File metadata and controls
109 lines (97 loc) · 3.81 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
106
107
108
109
class stackNode:
def __init__(self,data):
self.data = data
self.next = None
class stack:
def __init__(self):
self.top = None
self.operator = ['+','-','*','^','/']
self.priority = {'/':3,'+':2,'-':1,'*':4,'^':5}
def push(self,data):
newnode = stackNode(data)
newnode.next = self.top
self.top = newnode
def pop(self):
if(self.top.next !=None):
self.top = self.top.next
else:
self.top = None
def isempty(self):
if(self.top==None):
return True
def priorityfunc(self,char,temp):
if(self.priority[char] <= self.priority[temp]):
if(self.priority[char] < self.priority[temp]):
print(self.top.data,end=" ")
obj.pop()
obj.push(char)
elif(self.priority[char] == self.priority[temp]):
print(char,end=" ")
obj.pop()
obj.push(char)
else:
obj.push(char)
def evaluate(self,exp):
for char in exp:
if(char in self.operator):
if(self.top==None):
obj.push(char)
else:
value = self.top.data
#Down Oper
if(value in self.operator):
if(self.priority[char] <= self.priority[value]):
if(self.priority[char] < self.priority[value]):
print(self.top.data,end=" ")
obj.pop()
if(self.top!=None):
while(True):
if(self.top==None):
break
elif(self.priority[char] < self.priority[self.top.data]):
print(self.top.data,end=" ")
obj.pop()
else:
break
obj.push(char)
elif(self.priority[char] == self.priority[value]):
print(char,end=" ")
continue
else:
obj.push(char)
else:
print(self.top.data,end=" ")
obj.pop()
if(char not in self.operator):
obj.push(char)
else:
if(self.top==None):
obj.push(char)
else:
if self.top.data in self.operator:
temp= self.top.data
obj.priorityfunc(char,temp)
else:
obj.push(char)
elif(char == '('):
obj.push(char)
elif(char.isalpha() or char.isdigit()):
obj.push(char)
elif(char == ')'):
tempx = self.top
while(tempx.data !='('):
print(tempx.data,end=" ")
obj.pop()
tempx = tempx.next
obj.pop()
tempx=None
if(obj.isempty()!=True):
tempx = self.top
while(tempx):
print(tempx.data,end=" ")
obj.pop()
tempx = tempx.next
if __name__ == '__main__':
exp = '(a+b)*c-(d-e)*(f+g)'
obj = stack()
obj.evaluate(exp)