From 0fa443ce1a234704898630c188640f4512e9f7d1 Mon Sep 17 00:00:00 2001 From: Yuan Yuan Date: Thu, 26 Dec 2024 14:03:38 -0600 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20150=E9=A2=98=E6=9B=B4=E6=AD=A3Python?= =?UTF-8?q?=E8=A7=A3=E6=B3=95=E4=B8=AD=E4=BD=BF=E7=94=A8eval()=E7=9A=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 此处原本提供的两个python解法是一样的,并无区别;更正为实际上真正使用eval()的方法。 --- problems/0150.逆波兰表达式求值.md | 32 +++++++---------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 7d4031d7..4ffe950b 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -188,34 +188,20 @@ class Solution(object): return stack.pop() ``` -另一种可行,但因为使用eval相对较慢的方法: +另一种可行,但因为使用eval()相对较慢的方法: ```python -from operator import add, sub, mul - -def div(x, y): - # 使用整数除法的向零取整方式 - return int(x / y) if x * y > 0 else -(abs(x) // abs(y)) - class Solution(object): - op_map = {'+': add, '-': sub, '*': mul, '/': div} - - def evalRPN(self, tokens): - """ - :type tokens: List[str] - :rtype: int - """ + def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: - if token in self.op_map: - op1 = stack.pop() - op2 = stack.pop() - operation = self.op_map[token] - stack.append(operation(op2, op1)) + # 判断是否为数字,因为isdigit()不识别负数,故需要排除第一位的符号 + if token.isdigit() or (len(token)>1 and token[1].isdigit()): + stack.append(token) else: - stack.append(int(token)) - return stack.pop() - - + op2 = stack.pop() + op1 = stack.pop() + stack.append(str(int(eval(op1 + token + op2)))) + return int(stack.pop()) ``` ### Go: From 0638ba5ad88909b1463ccb43f55cb06f9bc88d09 Mon Sep 17 00:00:00 2001 From: Yuan Yuan Date: Thu, 26 Dec 2024 14:09:06 -0600 Subject: [PATCH 2/2] =?UTF-8?q?docs:=20150=E9=A2=98=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0150.逆波兰表达式求值.md | 1 + 1 file changed, 1 insertion(+) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 4ffe950b..5fb28c29 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -200,6 +200,7 @@ class Solution(object): else: op2 = stack.pop() op1 = stack.pop() + # 由题意"The division always truncates toward zero",所以使用int()可以天然取整 stack.append(str(int(eval(op1 + token + op2)))) return int(stack.pop()) ```