From 02fcd2c4a8f12782529b0fa787d3fd3f1f0fdca7 Mon Sep 17 00:00:00 2001 From: Eyjan_Huang <81480748+Eyjan-Huang@users.noreply.github.com> Date: Fri, 20 Aug 2021 17:14:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200150.=E9=80=86=E6=B3=A2?= =?UTF-8?q?=E5=85=B0=E8=A1=A8=E8=BE=BE=E5=BC=8F=E6=B1=82=E5=80=BC.md=20pyt?= =?UTF-8?q?hon=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用format string提升效率,增加可读性,避免使用索引访问,直接使用切片。 --- problems/0150.逆波兰表达式求值.md | 24 ++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 2b294337..bcde7d5b 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -223,17 +223,19 @@ var evalRPN = function(tokens) { python3 ```python -def evalRPN(tokens) -> int: - stack = list() - for i in range(len(tokens)): - if tokens[i] not in ["+", "-", "*", "/"]: - stack.append(tokens[i]) - else: - tmp1 = stack.pop() - tmp2 = stack.pop() - res = eval(tmp2+tokens[i]+tmp1) - stack.append(str(int(res))) - return stack[-1] +class Solution: + def evalRPN(self, tokens: List[str]) -> int: + stack = [] + for item in tokens: + if item not in {"+", "-", "*", "/"}: + stack.append(item) + else: + first_num, second_num = stack.pop(), stack.pop() + stack.append( + int(eval(f'{second_num} {item} {first_num}')) # 第一个出来的在运算符后面 + ) + return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的 + ```