Advertisement
dimonbb

simple calculator

Feb 19th, 2020
533
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. import re
  2. import collections
  3. import itertools
  4.  
  5. RE_TOKEN = re.compile('([()])|([+-])|([0-9]+)')
  6.  
  7. class Solution:
  8.     def calculate(self, s: str) -> int:
  9.         stack = []
  10.         for val in itertools.chain('(', (t.group(0) for t in RE_TOKEN.finditer(s)), ')'):
  11.             if val == ')':
  12.                 cur = 0
  13.                 while True:
  14.                     el = stack.pop()
  15.                     if el == '(':
  16.                         stack.append(cur+pp)
  17.                         break
  18.                     elif el == '+':
  19.                         cur += pp
  20.                     elif el == '-':
  21.                         cur -= pp
  22.                     else:
  23.                         pp = int(el)
  24.             else:
  25.                 stack.append(val)
  26.         return stack[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement