Advertisement
kosievdmerwe

Untitled

Sep 11th, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. class Solution:
  2.     def calculate(self, s: str) -> int:
  3.         tokens = []
  4.         for c in s:
  5.             if c == " ":
  6.                 continue
  7.             if c in "+-()":
  8.                 tokens.append(c)
  9.                 continue
  10.             c = int(c)
  11.             if not tokens or type(tokens[-1]) is str:
  12.                 tokens.append(c)
  13.                 continue
  14.             tokens[-1] = tokens[-1] * 10 + c
  15.  
  16.         def calc(start_idx):
  17.             """This always starts either at idx = 0 or after a opening bracket"""
  18.             result = 0
  19.             mult = 1
  20.             i = start_idx
  21.             while i < len(tokens):
  22.                 token = tokens[i]
  23.                 i += 1
  24.                 if token == "-":
  25.                     mult = -1
  26.                     continue
  27.                 if token == "+":
  28.                     continue
  29.                 if token == ")":
  30.                     break
  31.                    
  32.                 if token == "(":
  33.                     to_add, new_idx = calc(i)
  34.                     result += mult * to_add
  35.                     i = new_idx
  36.                 else:  # token is int
  37.                     result += mult * token
  38.                 mult = 1
  39.             return result, i
  40.         return calc(0)[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement