Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- @staticmethod
- def simple_calc(s: str) -> int:
- s = s.replace('--', '+')
- s = s.replace('+-', '-')
- total, num, plus = 0, 0, True
- for c in s:
- if '+' == c:
- total = total + int(num) if plus else total - int(num)
- num = 0
- plus = True
- continue
- if '-' == c:
- total = total + int(num) if plus else total - int(num)
- num = 0
- plus = False
- continue
- num = num*10 + int(c)
- total = total + int(num) if plus else total - int(num)
- return total
- def simplify(self, s: str) -> str:
- i, open = -1, -1
- for c in s:
- i += 1
- if '(' == c: open = i
- if ')' == c:
- s = s[0:open] + str(self.simple_calc(s[open + 1:i])) + s[i + 1:]
- return s
- return s
- def calculate(self, s: str) -> int:
- s = s.replace(' ', '')
- while '(' in s:
- s = self.simplify(s)
- return self.simple_calc(s)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement