Created
November 18, 2019 02:07
-
-
Save laike9m/d63a4ba140a5e477bf049c34fe420e84 to your computer and use it in GitHub Desktop.
Basic Calculator III
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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