-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinfix2postfix.py
More file actions
executable file
·63 lines (45 loc) · 1.23 KB
/
Copy pathinfix2postfix.py
File metadata and controls
executable file
·63 lines (45 loc) · 1.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
#!/usr/bin/env python2.7
from stack import Stack
from node import Node
precedence = {'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3
}
s = Stack()
def is_operand(ch):
return ch.isalpha()
def not_greater(token):
try:
if precedence[token] <= precedence[s.head.data]:
return True
except KeyError:
return False
def infix2postfix(expr):
# initialize stack
# s.push(Node('('))
postfix = []
for token in expr:
if is_operand(token):
postfix.append(token)
elif token == '(':
s.push(Node(token))
elif token == ')':
while not s.is_empty() and s.head.data != '(':
a = s.pop()
postfix.append(a.data)
if not s.is_empty() and s.head.data != '(':
return -1
else:
s.pop()
else:
while not s.is_empty() and not_greater(token):
postfix.append(s.pop().data)
s.push(Node(token))
while not s.is_empty():
postfix.append(s.pop().data)
print "".join(postfix)
if __name__ == "__main__":
exp = "a+b*(c^d-e)^(f+g*h)-i"
infix2postfix(exp)