Evaluate a Nested Let/Add/Mult Expression, or Report Invalid
StringsAuto-graded · 28 test casesLast updated
Tokenize, validate and evaluate a small Lisp-like language with scoped let bindings, returning None for any malformed or ill-formed input.
You are given a string expr that is meant to hold one expression in a tiny Lisp-style language. Evaluate it and return the resulting integer. If the string is not a well-formed expression, or evaluating it would read an undefined variable, return None.
Language
An expression is one of the following:
- Integer: an optional leading
-followed by one or more ASCII digits (for example7,-12,007,-0). A leading+is not allowed. - Variable: a lowercase letter followed by any number of lowercase letters or digits (for example
x,a1,add). Its value is the one bound by the nearest enclosingletthat defines it. - Addition:
(add e1 e2), which evaluates to the value ofe1plus the value ofe2. - Multiplication:
(mult e1 e2), which evaluates to the value ofe1times the value ofe2. - Binding form:
(let v1 e1 v2 e2 ... vk ek body), withk >= 1. Eachviis a variable name, eacheiandbodyis an expression. Pairs are processed left to right. The expressioneiis evaluated with the bindingsv1..v(i-1)already visible. If a name is bound more than once in the samelet, the later binding replaces the earlier one from that point on. The value of the form is the value ofbody, evaluated with allkbindings visible. Bindings made by aletare visible only inside thatletand shadow any outer binding of the same name.
Tokens and well-formedness
- The input is split into tokens:
(,), and maximal runs of characters that are neither whitespace nor parentheses. Whitespace only separates tokens and is otherwise ignored. - Every non-parenthesis token must be a valid integer or a valid variable, as defined above. Anything else (such as
1a,x_y,+5,ADD,abc!) makes the input invalid. - The words
add,multandletare operators only when they appear immediately after(. Anywhere else they are ordinary variable names, so(let add 1 add)is valid and evaluates to1. - A parenthesized form must start with exactly one of the operators
add,mult,let, have exactly the operands described above, and be closed by its matching). - The whole string must be exactly one expression. An empty or all-whitespace string, extra tokens after the expression, and unmatched parentheses are all invalid.
- Reading a variable that has no binding in scope is invalid. An error anywhere in the string makes the whole result
None, even in a part that would not affect the final value.
Return the integer value of a valid expression, or None otherwise.
Constraints
expris a string; its length may be zero.- A bare integer or a bare bound-in-scope variable is a valid expression, but a bare unbound variable is not.
- Integers in the input and intermediate results may be arbitrarily large (Python integers).
- Very deeply nested input must not crash the program; return
Noneif it cannot be processed.
Examples
Example 1
Input: evaluate_lisp_or_none('(add 1 2)')
Output: 3
Example 2
Input: evaluate_lisp_or_none('(mult 3 (add 2 3))')
Output: 15
Example 3
Input: evaluate_lisp_or_none('(let x 2 (mult x 5))')
Output: 10
Example 4
Input: evaluate_lisp_or_none('(add 1)')
Output: None
Example 5
Input: evaluate_lisp_or_none('(foo 1 2)')
Output: None
Example 6
Input: evaluate_lisp_or_none('(add 1 2')
Output: None
Hints
Hint 1
Split the text into tokens first: a parenthesis is its own token, and everything else is a run of non-space, non-parenthesis characters. Validate each atom against the integer and variable patterns.
Hint 2
Write a recursive function that reads exactly one expression starting at a shared position and returns its value. Raise an exception on any violation and convert it to None once at the top level.
Hint 3
For let, give each form its own copy of the scope. Inside it, an item is the final body exactly when it is an expression followed by `)`; otherwise it must be a variable name followed by a value expression. Require at least one pair, and after the top-level expression check that no tokens remain.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution is a recursive-descent evaluator in which every grammar violation raises an exception. One try/except at the top level turns any exception into None, so validation and evaluation happen in a single pass.
- Tokenize. A regex splits the string into
(,)and maximal runs of characters that are neither whitespace nor parentheses. A string with no tokens is invalid. Every atom stays a single token, so something likeabc!is kept whole and rejected later. - Parse and evaluate recursively.
parse_expr(env)reads from a shared position and consumes exactly one expression.- An integer token matches
-?\d+and returns its value. - A variable token matches
[a-z][a-z0-9]*and must be present inenv, otherwise it raises. - A
(must be followed byadd,multorlet. Foraddandmult, parse two operands and require). - Any other token raises.
- An integer token matches
- Handle
let. Theletform is the only place where the next item is ambiguous: a name such asxcould be a binding name or the final body. The parser resolves this with a small bounded backtrack.- Copy the environment (
local = dict(env)), so bindings are scoped to thisletand shadow outer ones. - Try to parse the next item as an expression. If it parses and the following token is
), it is the body. This counts only if at least one binding was made, otherwise it raises. - If that attempt fails or is not followed by
), reset the position and read a binding: the token must be a variable name, followed by a value expression evaluated inlocal. Then loop. - A
)where a binding or body should start raises, which rejects(let)and(let x 1).
- Copy the environment (
- Finish. After the top-level expression, every token must have been consumed.
Why it is correct
- Every successful return follows a grammar rule exactly: atoms fully match their patterns, operators are exactly the three allowed words, parentheses are closed where expected, and leftover tokens are rejected.
- In a valid
let, a body is always followed by), while a binding name is always followed by its value, never by). So "try body first, otherwise binding" picks the correct reading. If the item is a bound or unbound variable that is really a binding name, the trial either fails or sees a non-)next token and falls back. - The trial parse has no side effects on the caller's scope, because nested
letforms write only to their own copy. Resetting the position is therefore safe. - Copying the scope per
letgives lexical scoping, left-to-right sequential bindings and innermost-wins shadowing. Keywords are checked only right after(, so they remain usable as variable names elsewhere. RecursionErroris caught, so extremely deep nesting yieldsNone.
Complexity
- Time: O(n · v), where n is the number of tokens and v the number of variables in scope. Parsing is linear because a failed trial either touches one atom or leads to an error that propagates upward. Copying the scope for each
letcontributes the factor v. - Space: O(n) for the tokens and recursion depth, plus the scope copies along the current nesting path.
Reference solution
import re
import sys
from typing import Optional
def evaluate_lisp_or_none(expr: str) -> Optional[int]:
sys.setrecursionlimit(100000)
tokens = []
pos = 0
for match in re.finditer(r'\(|\)|[^\s()]+', expr):
if expr[pos:match.start()].strip():
return None
tokens.append(match.group())
pos = match.end()
if expr[pos:].strip():
return None
if not tokens:
return None
integer = re.compile(r'-?\d+$')
variable = re.compile(r'[a-z][a-z0-9]*$')
index = 0
def parse_expr(env):
nonlocal index
if index >= len(tokens):
raise ValueError
token = tokens[index]
if token == ')' or token == '(':
if token == ')':
raise ValueError
index += 1
if index >= len(tokens):
raise ValueError
operator = tokens[index]
index += 1
if operator not in ('add', 'mult', 'let'):
raise ValueError
if operator == 'add' or operator == 'mult':
left = parse_expr(env)
right = parse_expr(env)
if index >= len(tokens) or tokens[index] != ')':
raise ValueError
index += 1
return left + right if operator == 'add' else left * right
local = dict(env)
bindings = 0
while True:
if index >= len(tokens):
raise ValueError
if tokens[index] == ')':
raise ValueError
start = index
try:
result = parse_expr(local)
if index < len(tokens) and tokens[index] == ')':
index += 1
if bindings == 0:
raise ValueError
return result
except ValueError:
pass
index = start
if index >= len(tokens) or not variable.fullmatch(tokens[index]):
raise ValueError
name = tokens[index]
index += 1
local[name] = parse_expr(local)
bindings += 1
if integer.fullmatch(token):
index += 1
return int(token)
if variable.fullmatch(token):
index += 1
if token not in env:
raise ValueError
return env[token]
raise ValueError
try:
result = parse_expr({})
if index != len(tokens):
return None
return result
except (ValueError, RecursionError):
return None