227 Basic Calculator II
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5.import operator
import re
map_op = {'+': operator.add, '-': operator.sub,
'*': operator.mul, '/': operator.truediv}
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
s = "".join(s.split())
tokens = re.split('( |\+|\/|\-|\*)', s)
self._calculateP1(tokens)
return self._calculateP2(tokens)
def _calculateP1(self, tokens):
if '*' not in tokens and '/' not in tokens:
return
for i, token in enumerate(tokens):
if token is '*' or token is '/':
calc = int(map_op[token](int(tokens[i-1]), int(tokens[i+1])))
tokens[i-1] = str(calc)
del tokens[i:i+2]
return self._calculateP1(tokens)
def _calculateP2(self, tokens):
if len(tokens) is 1:
return int(tokens[0])
for i, token in enumerate(tokens):
if token is '+' or token is '-':
calc = int(map_op[token](int(tokens[i-1]), int(tokens[i+1])))
tokens[i-1] = str(calc)
del tokens[i:i+2]
return self._calculateP2(tokens)Last updated