-
-
Save PetterS/fcbd82c33c2f3e6780de0312e17542e7 to your computer and use it in GitHub Desktop.
This file contains 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 Evaluator: | |
def __init__(self, string): | |
self.tokens = re.findall(r"\d+|\*|\+|\(|\)", string) | |
self.pos = 0 | |
def next(self): | |
self.pos += 1 | |
return self.tokens[self.pos - 1] | |
def consume(self, token): | |
if self.pos < len(self.tokens) and self.tokens[self.pos] == token: | |
self.next() | |
return True | |
else: | |
return False | |
def evaluate_term(self): | |
if self.consume("("): | |
subexpr = self.evaluate() | |
assert self.consume(")") | |
return subexpr | |
else: | |
return int(self.next()) | |
def evaluate(self): | |
result = self.evaluate_term() | |
while True: | |
if self.consume("+"): | |
result += self.evaluate_term() | |
elif self.consume("*"): | |
result *= self.evaluate_term() | |
else: | |
break | |
return result | |
assert Evaluator("2 * 3 + (4 * 5)").evaluate() == 26 | |
assert Evaluator("5 + (8 * 3 + 9 + 3 * 4 * 3)").evaluate() == 437 | |
assert Evaluator("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))").evaluate() == 12240 | |
assert Evaluator("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2").evaluate() == 13632 | |
class Evaluator2(Evaluator): | |
def parse_sum(self): | |
result = self.evaluate_term() | |
while self.consume("+"): | |
result += self.evaluate_term() | |
return result | |
def evaluate(self): | |
result = self.parse_sum() | |
while self.consume("*"): | |
result *= self.parse_sum() | |
return result | |
assert Evaluator2("1 + (2 * 3) + (4 * (5 + 6))").evaluate() == 51 | |
assert Evaluator2("2 * 3 + (4 * 5)").evaluate() == 46 | |
assert Evaluator2("5 + (8 * 3 + 9 + 3 * 4 * 3)").evaluate() == 1445 | |
assert Evaluator2("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))").evaluate() == 669060 | |
assert Evaluator2("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2 ").evaluate() == 23340 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment