-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshunting_yard.py
101 lines (82 loc) · 2.39 KB
/
shunting_yard.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from collections import deque
class Stack:
def __init__(self):
self.__stack = []
def top(self):
return self.__stack[-1]
def pop(self):
self.__stack.pop()
def push(self, value):
self.__stack.append(value)
def empty(self):
return not bool(self.__stack)
class Queue:
def __init__(self):
self.__queue = deque()
def enqueue(self, value):
self.__queue.append(value)
def dequeue(self):
self.__queue.popleft()
def top(self):
return self.__queue[0]
def empty(self):
return not bool(self.__queue)
def __iter__(self):
return iter(self.__queue)
precedence = {
"*" : 10,
"/" : 10,
"+" : 9,
"-" : 9,
"(" : -1,
")" : -1,
}
operations = {
"*" : lambda x, y: x * y,
"/" : lambda x, y: x / y,
"+" : lambda x, y: x + y,
"-" : lambda x, y: x - y,
}
expr = ["3", "/", "2", "/", "1"]
def infixTOprefix(expr, precedence):
stack = Stack()
output = Queue()
for token in expr:
if token not in precedence:
output.enqueue(token)
elif token == ")":
while not stack.empty():
if stack.top() == "(":
stack.pop()
break
else:
output.enqueue(stack.top())
stack.pop()
else:
if stack.empty() or token == "(":
stack.push(token)
else:
while not stack.empty() and precedence[token] <= precedence[stack.top()]:
output.enqueue(stack.top())
stack.pop()
stack.push(token)
while not stack.empty():
output.enqueue(stack.top())
stack.pop()
return list(output)
def evaluate(expr, operations):
stack = Stack()
for token in expr:
if token not in operations:
stack.push(float(token))
else:
a = stack.top()
stack.pop()
b = stack.top()
stack.pop()
stack.push(operations[token](b, a))
return stack.top()
prefix = infixTOprefix(expr, precedence)
print expr
print prefix
print evaluate(prefix, operations)