-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfix.py
More file actions
109 lines (80 loc) · 2.23 KB
/
InfixToPostfix.py
File metadata and controls
109 lines (80 loc) · 2.23 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 Stack:
def __init__(self, size):
self.stack = []
self.size = size
def push(self, item):
if len(self.stack) < self.size:
self.stack.append(item)
def pop(self):
result = -1
if self.stack != []:
result = self.stack.pop()
return result
def show(self):
if self.stack == []:
print("Stack is empty!")
else:
print("Stack data:")
for item in reversed(self.stack):
print(item)
def isEmpty(self):
return self.stack == []
def firstChar(self):
result = -1
if self.stack != []:
result = self.stack[len(self.stack) - 1]
return result
def isOperand(c):
return c >= 'A' and c <= 'Z'
operators = "+-*/^"
def isOperator(c):
return c in operators
def getPrecedence(c):
result = 0
for char in operators:
result += 1
if char == c:
if c in '-/':
result -= 1
break
return result
def toPostfix(expression):
result = ""
stack = Stack(30)
for char in expression:
if isOperand(char):
result += char
elif isOperator(char):
while True:
firstChar = stack.firstChar()
if stack.isEmpty() or firstChar == '(':
stack.push(char)
break
else:
pC = getPrecedence(char)
pTC = getPrecedence(firstChar)
if pC > pTC:
stack.push(char)
break
else:
result += stack.pop()
elif char == '(':
stack.push(char)
elif char == ')':
cpop = stack.pop()
while cpop != '(':
result += cpop
cpop = stack.pop()
while not stack.isEmpty():
cpop = stack.pop()
result += cpop
return result
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# test
infixExps = [
'A*B+C', # AB*C+
'(A+B)/(C+D)+E*F*G+H/(K+M)'
]
for exp in infixExps:
postfix = toPostfix(exp)
print(f'Infix: {exp} -> Postfix: {postfix}')