Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 43 lines (37 sloc) 1.336 kb
726e343 Dolkar All
authored
1 from collections import deque
2
3 def shunting_yard(expr, operators, left_par = '(', right_par = ')'):
4 '''Infix to postfix notation convertor using shunting-yard algorithm'''
5 precedence = dict([(op, i) for i, op in enumerate(operators)])
6 precedence[left_par] = -1
7 precedence[right_par] = -1
8 operators = set(operators)
9
10 output = deque()
11 stack = deque()
12 for token in expr:
13 if token in operators:
14 while stack and precedence[stack[-1]] > precedence[token]:
15 output.append(stack.pop())
16 stack.append(token)
17 elif token == left_par:
18 stack.append(token)
19 elif token == right_par:
20 while stack:
21 if stack[-1] != left_par:
22 output.append(stack.pop())
23 else:
24 stack.pop()
25 break
26 else:
27 raise ValueError('Unbalanced parentheses')
28 else:
29 output.append(token)
30
31 stack.reverse()
32 for operator in stack:
33 if operator == left_par:
34 raise ValueError('Unbalanced parentheses')
35 output.append(operator)
36
37 return list(output)
38
8bd1c6c Dolkar Added readme.
authored
39 if __name__ == '__main__':
40 opers = ['or', 'and']
41 expr = ['(', 0, 'or', 1, ')', 'and', 2]
42 print shunting_yard(expr, opers)
Something went wrong with that request. Please try again.