Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def calculate(self, s: str) -> int:
- tokens = []
- for c in s:
- if c == " ":
- continue
- if c in "+-()":
- tokens.append(c)
- continue
- c = int(c)
- if not tokens or type(tokens[-1]) is str:
- tokens.append(c)
- continue
- tokens[-1] = tokens[-1] * 10 + c
- def calc(start_idx):
- """This always starts either at idx = 0 or after a opening bracket"""
- result = 0
- mult = 1
- i = start_idx
- while i < len(tokens):
- token = tokens[i]
- i += 1
- if token == "-":
- mult = -1
- continue
- if token == "+":
- continue
- if token == ")":
- break
- if token == "(":
- to_add, new_idx = calc(i)
- result += mult * to_add
- i = new_idx
- else: # token is int
- result += mult * token
- mult = 1
- return result, i
- return calc(0)[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement