@@ -169,8 +169,12 @@ class Solution {
169
169
``` python
170
170
from operator import add, sub, mul
171
171
172
- class Solution :
173
- op_map = {' +' : add, ' -' : sub, ' *' : mul, ' /' : lambda x , y : int (x / y)}
172
+ def div (x , y ):
173
+ # 使用整数除法的向零取整方式
174
+ return int (x / y) if x * y > 0 else - (abs (x) // abs (y))
175
+
176
+ class Solution (object ):
177
+ op_map = {' +' : add, ' -' : sub, ' *' : mul, ' /' : div}
174
178
175
179
def evalRPN (self , tokens : List[str ]) -> int :
176
180
stack = []
@@ -186,18 +190,31 @@ class Solution:
186
190
187
191
另一种可行,但因为使用eval相对较慢的方法:
188
192
``` python
189
- class Solution :
190
- def evalRPN (self , tokens : List[str ]) -> int :
193
+ from operator import add, sub, mul
194
+
195
+ def div (x , y ):
196
+ # 使用整数除法的向零取整方式
197
+ return int (x / y) if x * y > 0 else - (abs (x) // abs (y))
198
+
199
+ class Solution (object ):
200
+ op_map = {' +' : add, ' -' : sub, ' *' : mul, ' /' : div}
201
+
202
+ def evalRPN (self , tokens ):
203
+ """
204
+ :type tokens: List[str]
205
+ :rtype: int
206
+ """
191
207
stack = []
192
- for item in tokens:
193
- if item not in {" +" , " -" , " *" , " /" }:
194
- stack.append(item)
208
+ for token in tokens:
209
+ if token in self .op_map:
210
+ op1 = stack.pop()
211
+ op2 = stack.pop()
212
+ operation = self .op_map[token]
213
+ stack.append(operation(op2, op1))
195
214
else :
196
- first_num, second_num = stack.pop(), stack.pop()
197
- stack.append(
198
- int (eval (f ' { second_num} { item} { first_num} ' )) # 第一个出来的在运算符后面
199
- )
200
- return int (stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的
215
+ stack.append(int (token))
216
+ return stack.pop()
217
+
201
218
202
219
```
203
220
0 commit comments