leetcode150 Evaluate Reverse Polish Notation

 1 """
 2 Evaluate the value of an arithmetic expression in Reverse Polish Notation.
 3 Valid operators are +, -, *, /. Each operand may be an integer or another expression.
 4 Note:
 5     Division between two integers should truncate toward zero.
 6     The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
 7 Example 1:
 8 Input: ["2", "1", "+", "3", "*"]
 9 Output: 9
10 Explanation: ((2 + 1) * 3) = 9
11 Example 2:
12 Input: ["4", "13", "5", "/", "+"]
13 Output: 6
14 Explanation: (4 + (13 / 5)) = 6
15 Example 3:
16 Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
17 Output: 22
18 Explanation:
19   ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
20 = ((10 * (6 / (12 * -11))) + 17) + 5
21 = ((10 * (6 / -132)) + 17) + 5
22 = ((10 * 0) + 17) + 5
23 = (0 + 17) + 5
24 = 17 + 5
25 = 22
26 """
27 """
28 此题思路很简单,用栈即可实现,自己AC,但遇到三个麻烦
29 第一个是加减乘除操作要将字符型转为整型
30 第二个是被减数和减数的问题。先弹出的是减数,后弹出的是被减数。除法也需这样考虑
31 第三个是python向下取整的问题 -6 // 132 == -1
32 """
33 class Solution1:
34     def evalRPN(self, tokens):
35         if not tokens:
36             return 0
37         stack = []
38         for i in range(len(tokens)):
39             stack.append(tokens[i])
40             if tokens[i] == '+':
41                 stack.pop()
42                 x = int(stack.pop())
43                 y = int(stack.pop())
44                 stack.append(y+x)
45             if tokens[i] == '-':
46                 stack.pop()
47                 x = int(stack.pop())
48                 y = int(stack.pop())
49                 stack.append(y-x) #减法注意先出栈的是减数,同除法
50             if tokens[i] == '*':
51                 stack.pop()
52                 x = int(stack.pop())
53                 y = int(stack.pop())
54                 stack.append(y*x)
55             if tokens[i] == '/':
56                 stack.pop()
57                 x = int(stack.pop())
58                 y = int(stack.pop())
59                 if x > 0 and y < 0 or x < 0 and y > 0:
60                     stack.append(-(abs(y)//abs(x)))
61                 else:                    #6//-132 == -1,python的向下取整,所以加了这条语句
62                     stack.append(y//x)
63         return stack.pop()
64 
65 if __name__ == '__main__':
66     ans = Solution1()
67     x = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
68     s = ans.evalRPN(x)
69     print(s)
70 
71 print(6//-132)
原文地址:https://www.cnblogs.com/yawenw/p/12387613.html