From 6d5259d0ae4d508a472e8c1da07f4c4d20939798 Mon Sep 17 00:00:00 2001 From: Pavel Karateev Date: Sat, 26 Oct 2024 12:31:27 +0200 Subject: [PATCH] re-solve "224. Basic Calculator" --- src/basic_calculator.py | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/src/basic_calculator.py b/src/basic_calculator.py index 4ea93d8..287839b 100644 --- a/src/basic_calculator.py +++ b/src/basic_calculator.py @@ -1,30 +1,33 @@ +SIGN = { + "+": +1, + "-": -1, +} + + class Solution: def calculate(self, s: str) -> int: - num, sign, stack = 0, 1, [0] + current, sign, stack = 0, +1, [0] for x in s: - if x.isnumeric(): - num = num * 10 + int(x) + if x.isdigit(): + current = current * 10 + int(x) elif x == " ": - continue - elif x == "+": - stack[-1] += num * sign - sign = 1 - num = 0 - elif x == "-": - stack[-1] += num * sign - sign = -1 - num = 0 + pass + elif x in SIGN: + stack[-1] += current * sign + sign = SIGN[x] + current = 0 elif x == "(": - stack.extend([sign, 0]) + stack.append(sign) + stack.append(0) sign = 1 - num = 0 + current = 0 elif x == ")": - last = (stack.pop() + num * sign) * stack.pop() + last = (stack.pop() + current * sign) * stack.pop() stack[-1] += last sign = 1 - num = 0 + current = 0 else: - raise ValueError("unknown token: {x}") + raise ValueError(f"unknown token: {x}") - return stack[-1] + num * sign + return stack[-1] + current * sign