classSolution: defcalculate(self, s: str) -> int: tokens = self.reverse_polish(self.tokenize(s)) stack = [] for token in tokens: ifisinstance(token, int): stack.append(token) else: b, a = stack.pop(), stack.pop() if token == '+': stack.append(a + b) elif token == '-': stack.append(a - b) elif token == '*': stack.append(a * b) elif token == '/': stack.append(a // b)
return stack[0]
deftokenize(self, expr: str) -> Iterator[Token]: n = len(expr) left = 0 for i, c inenumerate(expr): if c.isdigit(): continue if left < i: yieldint(expr[left:i]) # A number. if c != ' ': yield c # An operator. left = i + 1
if left < n: yieldint(expr[left:]) # The last number.
defreverse_polish(self, tokens: Iterator[Token]) -> Iterator[Token]: ops = [] levels= {'+': 1, '-': 1, '*': 2, '/': 2} for token in tokens: ifisinstance(token, int): yield token else: p = levels[token] while ops and levels[ops[-1]] >= p: yield ops.pop() ops.append(token)
classSolution: defcalculate(self, s: str) -> int: vals = [] num = 0 prev_op = '+'# Default to `+`, means the 1st number is positive. n = len(s) for i inrange(n + 1): c = s[i] if i < n else'=' if c.isdigit(): num = num * 10 + int(c) elif c == ' ': continue else: if prev_op == '+': vals.append(num) elif prev_op == '-': vals.append(-num) elif prev_op == '*': vals.append(vals.pop() * num) else: vals.append(trunc(vals.pop() / num))