-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfixTopostfix.py
79 lines (67 loc) · 2.08 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# -*- coding: utf-8 -*-
# convert infix expression to postfix expression
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def size(self):
return len(self.items)
# get the top value of stack, but not remove it.
def peek(self):
return self.items[len(self.items)-1]
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def infix_to_postfix(expr):
# precedence
prec = {'*': 5, '/': 5, '+': 3, '-': 3, '(': 2}
output = []
op_stack = Stack()
expr_list = expr.split(' ')
for char in expr_list:
if char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
output.append(char)
elif char == '(':
op_stack.push(char)
elif char == ')':
while op_stack.peek() != '(':
output.append(op_stack.pop())
op_stack.pop()
else:
while (not op_stack.is_empty()) and (prec[op_stack.peek()] > prec[char]):
output.append(op_stack.pop())
op_stack.push(char)
while not op_stack.is_empty():
output.append(op_stack.pop())
return ''.join(output)
print(infix_to_postfix('A * B + C * D'))
print(infix_to_postfix('( A + B ) * ( C + D )'))
# calculate postfix
def postfix_eval(expr):
val_stack = Stack()
for char in expr:
if char in '0123456789':
val_stack.push(int(char))
elif char == '+':
s2 = val_stack.pop()
s1 = val_stack.pop()
s = s1 + s2
val_stack.push(s)
elif char == '-':
s2 = val_stack.pop()
s1 = val_stack.pop()
s = s1 -s2
val_stack.push(s)
elif char == '*':
s2 = val_stack.pop()
s1 = val_stack.pop()
s = s1 * s2
val_stack.push(s)
elif char == '/':
s2 = val_stack.pop()
s1 = val_stack.pop()
s = s1 / s2
val_stack.push(s)
return val_stack.pop()