From 0e1cc6d2771113ef0caeed9a26ec0e7e590e91e7 Mon Sep 17 00:00:00 2001 From: Meliodas417 <76930518+Meliodas417@users.noreply.github.com> Date: Sun, 24 Mar 2024 11:07:42 -0500 Subject: [PATCH] =?UTF-8?q?Update=200150.=E9=80=86=E6=B3=A2=E5=85=B0?= =?UTF-8?q?=E8=A1=A8=E8=BE=BE=E5=BC=8F=E6=B1=82=E5=80=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 除法逻辑不完整,假如是5/2=2没问题,但如果是-5/2,会向下取整,就变成-3了,可以单独定义一个函数。 底下最先弹出的数字实际上是最后进入的数字,也就是运算符右边的操作数,而第二个弹出的数字是第一个进入的数字,即运算符左边的操作数。stack.append(operation(op2, op1)) --- problems/0150.逆波兰表达式求值.md | 41 ++++++++++++++++------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 663a68ea..fd4d0726 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -169,8 +169,12 @@ class Solution { ```python from operator import add, sub, mul -class Solution: - op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)} +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: List[str]) -> int: stack = [] @@ -186,18 +190,31 @@ class Solution: 另一种可行,但因为使用eval相对较慢的方法: ```python -class Solution: - def evalRPN(self, tokens: List[str]) -> int: +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 + """ stack = [] - for item in tokens: - if item not in {"+", "-", "*", "/"}: - stack.append(item) + 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)) else: - first_num, second_num = stack.pop(), stack.pop() - stack.append( - int(eval(f'{second_num} {item} {first_num}')) # 第一个出来的在运算符后面 - ) - return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的 + stack.append(int(token)) + return stack.pop() + ```