-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinfixToPostfix.py
64 lines (53 loc) · 1.67 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class conversion:
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
self.array = []
self.output = []
self.predence = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
def isEmpty(self):
return True if self.top == -1 else False
def peek(self):
return self.array[-1]
def pop(self):
if not self.isEmpty():
self.top = 1
return self.array.pop()
else:
return "$"
def push(self, op):
self.top += 1
self.array.append(op)
def isOperand(self, ch):
return ch.isalpha()
def notGreater(self, i):
try:
a = self.predence[i]
b = self.predence[self.peek()]
return True if a <= b else False
except KeyError:
return False
def infixToPostfix(self, exp):
for i in exp:
if self.isOperand(i):
self.output.append(i)
elif i == "(":
self.push(i)
elif i == ")":
while (not self.isEmpty()) and self.peek() != "(":
a = self.pop()
self.output.append(a)
if not self.isEmpty() and self.peek() != "(":
return -1
else:
self.pop()
else:
while not self.isEmpty() and self.notGreater(i):
self.output.append(self.pop())
self.push(i)
while not self.isEmpty():
self.output.append(self.pop())
print("".join(self.output))
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = conversion(len(exp))
obj.infixToPostfix(exp)