-
Notifications
You must be signed in to change notification settings - Fork 90
/
Convert Expression to Reverse Polish Notation.py
58 lines (48 loc) · 1.54 KB
/
Convert Expression to Reverse Polish Notation.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
"""
Given an expression string array, return the Reverse Polish notation of this expression. (remove the parentheses)
Example
For the expression [3 - 4 + 5] (which denote by ["3", "-", "4", "+", "5"]), return [3 4 - 5 +] (which denote by ["3",
"4", "-", "5", "+"])
"""
__author__ = 'Daniel'
class Solution:
def convertToRPN(self, expression):
"""
:param expression: A string list
:return: The Reverse Polish notation of this expression
"""
return self.infix2postfix(expression)
def infix2postfix(self, lst):
"""
The stack temporarily stores the operators of strictly increasing precedence order.
:param lst:
:return:
"""
stk = []
ret = [] # post fix
for elt in lst:
if elt.isdigit():
ret.append(elt)
elif elt == "(":
stk.append(elt)
elif elt == ")":
while stk and stk[-1] != "(":
ret.append(stk.pop())
stk.pop()
else:
while stk and self.precedence(elt) <= self.precedence(stk[-1]):
ret.append(stk.pop())
stk.append(elt)
while stk:
ret.append(stk.pop())
return ret
def precedence(self, x):
if x in ("(", ")"):
return 0
if x in ("+", "-"):
return 1
if x in ("*", "/"):
return 2
return 3
if __name__ == "__main__":
print Solution().infix2postfix(["3", "-", "4", "+", "5"])