Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import re
# Supported tokens and their operations
scanner = re.Scanner([
(r"([0-9]+)", lambda x, y: int(y)),
(r"\+", lambda x, y: "ADD"),
(r"-", lambda x, y: "SUBTRACT"),
(r"\*", lambda x, y: "MULTIPLY"),
(r"/", lambda x, y: "DIVIDE"),
(r"\s+", lambda x, y: None),
], flags=re.DOTALL)
def operation_multiply(a, b):
return a * b
def operation_divide(a, b):
return a / b
def operation_add(a, b):
return a + b
def operation_subtract(a, b):
return a - b
def interpret(results):
assert isinstance(results[0], int) and isinstance(results[-1], int), "Trailing operators were encoutered!"
if len(results) == 1:
return results[0]
for operation in reversed(ORDER_OF_OPERATIONS):
boundary = results.index(operation)
return globals()["operation_%s" % operation.lower()](
except ValueError:
assert False, "Missing an operator"
def evaluate(expression):
results, remainder = scanner.scan(expression)
assert not remainder, "Some of the input couldn't be interpreted"
return interpret(results)
assert evaluate("14 + 2 * 3 - 6 / 2") == 17
assert evaluate("(1 + 2) * 3") == 9
assert evaluate("__import__('os').remove('foobar.file')")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.