From abedcbbe040fff779f54ed7a68204e677bcaa24e Mon Sep 17 00:00:00 2001 From: Frank Mao Date: Fri, 6 Jan 2023 00:35:56 +0800 Subject: [PATCH] =?UTF-8?q?0150.=E9=80=86=E6=B3=A2=E5=85=B0=E8=A1=A8?= =?UTF-8?q?=E8=BE=BE=E5=BC=8F=E6=B1=82=E5=80=BC=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=9B=B4=E5=BF=AB=E9=80=9F=E7=9A=84python=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0150.逆波兰表达式求值.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 176ea687..f0323bc4 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -163,6 +163,25 @@ class Solution { python3 +```python +from operator import add, sub, mul + +class Solution: + op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)} + + def evalRPN(self, tokens: List[str]) -> int: + stack = [] + for token in tokens: + if token not in {'+', '-', '*', '/'}: + stack.append(int(token)) + else: + op2 = stack.pop() + op1 = stack.pop() + stack.append(self.op_map[token](op1, op2)) # 第一个出来的在运算符后面 + return stack.pop() +``` + +另一种可行,但因为使用eval相对较慢的方法: ```python class Solution: def evalRPN(self, tokens: List[str]) -> int: