Mini Interpreter
Completed
Interpret a tiny language. Each line is let NAME = EXPR or print EXPR, where EXPR is integers and variable names joined by + or - (spaces around operators). Lines run until end. Print error: undefined NAME for unknown variables.
Input
Program lines, then end.
Output
The program's output.
Example
Input
let x = 5 let y = x + 10 print y - 3 print z + 1 let x = x - x print x end
Output
12 error: undefined z 0
Editor
Python
Hints
Split the expression into tokens and keep a running total and the current sign.
Store variables in a dict.
Solution explanation
Parsing, an environment dict and an evaluation loop are the core of every interpreter, including Python itself.
Show solution
def evaluate(expr, env):
tokens = expr.split()
total = 0
sign = 1
for token in tokens:
if token == "+":
sign = 1
elif token == "-":
sign = -1
else:
if token.lstrip("-").isdigit():
value = int(token)
elif token in env:
value = env[token]
else:
raise NameError(token)
total += sign * value
return total
env = {}
while (line := input()) != "end":
try:
if line.startswith("let "):
name, expr = line[4:].split(" = ", 1)
env[name] = evaluate(expr, env)
elif line.startswith("print "):
print(evaluate(line[6:], env))
except NameError as err:
print(f"error: undefined {err}")