Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. class Solution:
  2. @staticmethod
  3. def simple_calc(s: str) -> int:
  4. s = s.replace('--', '+')
  5. s = s.replace('+-', '-')
  6. total, num, plus = 0, 0, True
  7. for c in s:
  8. if '+' == c:
  9. total = total + int(num) if plus else total - int(num)
  10. num = 0
  11. plus = True
  12. continue
  13. if '-' == c:
  14. total = total + int(num) if plus else total - int(num)
  15. num = 0
  16. plus = False
  17. continue
  18. num = num*10 + int(c)
  19.  
  20. total = total + int(num) if plus else total - int(num)
  21.  
  22. return total
  23.  
  24. def simplify(self, s: str) -> str:
  25. i, open = -1, -1
  26. for c in s:
  27. i += 1
  28. if '(' == c: open = i
  29. if ')' == c:
  30. s = s[0:open] + str(self.simple_calc(s[open + 1:i])) + s[i + 1:]
  31. return s
  32. return s
  33.  
  34. def calculate(self, s: str) -> int:
  35. s = s.replace(' ', '')
  36. while '(' in s:
  37. s = self.simplify(s)
  38. return self.simple_calc(s)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement