Skip to content

Instantly share code, notes, and snippets.

@laike9m
Created Nov 18, 2019
Embed
What would you like to do?
Basic Calculator III
class Solution:
"""
@param s: the expression string
@return: the answer
"""
def calculate(self, s):
i = 0
left_brac_indexes = []
while i < len(s):
char = s[i]
if char == "(":
left_brac_indexes.append(i)
i += 1
elif char == ")":
inner_result = str(
self.calculate_no_bracket(s[left_brac_indexes[-1] + 1 : i])
)
s = s[: left_brac_indexes[-1]] + inner_result + s[i + 1 :]
i = left_brac_indexes[-1] + len(inner_result)
left_brac_indexes.pop()
else:
i += 1
return self.calculate_no_bracket(s)
def calculate_no_bracket(self, s):
groups = (
s.replace("--", " + ")
.replace("+", " + ")
.replace("-", " - ")
.replace("*", " * ")
.replace("/", " / ")
.replace("-", "+ -1 *")
.strip()
.split("+")
)
return sum([self.calc(g) for g in groups])
@staticmethod
def calc(group: str):
if not group or group.isspace(): # Could be empty string, e.g. '+ 4'.split('+')
return 0
elems = group.strip().split()
result = int(elems[0])
for i in range(1, len(elems), 2):
if elems[i] == "*":
result *= int(elems[i + 1])
elif elems[i] == "/":
result = int(result / int(elems[i + 1]))
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment