Evaluate Nested Prefix Expressions with Scoped Bindings
Stacks & QueuesAuto-graded · 28 test casesLast updated
Parse and evaluate a parenthesized prefix language with sum, prod and set, handling lexical scoping, strict validation and 32-bit overflow rules.
Evaluate Nested Prefix Expressions with Scoped Bindings
You are given a string expr written in a small Lisp-like language. Compute its integer value. If the string is not a valid program, return the string "InvalidExpression" instead.
The language
An expression is either an atom or a parenthesized form.
Atoms
- An integer matches
-?[0-9]+: an optional leading-followed by one or more ASCII digits. Leading zeros are allowed, so007is 7 and-0is 0. - A variable matches
[a-z][a-z0-9]*: a lowercase letter followed by any number of lowercase letters or digits. - Any other atom (for example
1a,--1,-,+3,X,a_b) is malformed.
Parenthesized forms have the shape ( op ... ), where op is the first token after the opening parenthesis:
(sum e1 e2 ... ek)withk >= 2returns the sum of its sub-expressions.(prod e1 e2 ... ek)withk >= 2returns the product of its sub-expressions.(set x v body)takes exactly three parts.xmust be a raw variable token (not a parenthesized form).vandbodyare arbitrary expressions. The form first evaluatesv, then evaluatesbodywithxbound to that value, and returns the value ofbody.
Any other token in operator position is an error.
Scoping
- Bindings are lexical.
xis visible only inside thebodyof itsset, including any forms nested in that body. - An inner
setof the same name shadows the outer binding for its own body only. vis evaluated in the scope outside the new binding. For example,(set x 1 (set x (sum x 1) x))is2.- Once a
setform closes, its binding is gone. - Variable names are not restricted. A name such as
summay be bound bysetand then read as an ordinary variable atom. A token directly after(is always treated as the operator.
Tokenization
Parentheses are separate tokens even when they touch other text, so (sum 1 2) has the tokens (, sum, 1, 2, ). Any run of whitespace separates tokens, and extra whitespace is ignored. Every other maximal run of non-whitespace, non-parenthesis characters is one token.
32-bit range
Every value must stay within the signed 32-bit range [-2147483648, 2147483647]. A violation makes the whole expression invalid. The checks are:
- Each integer literal must be in range.
- For
sum, only the final total of that form is checked. Intermediate partial sums are not checked, so(sum 2147483647 1 -1)is2147483647. - For
prod, the arguments are multiplied left to right, starting from a running value of 1, and every running product must be in range. So(prod 65536 65536 0)is invalid even though the true product is 0.
Errors
Return "InvalidExpression" when any of these occurs:
- The input is empty or contains only whitespace.
- Parentheses are unbalanced, there is a stray
), or tokens remain after the top-level expression is complete (for example1 2or(sum 1 2))). ()is given, or the operator is unknown.- A form has the wrong arity or shape, including
setwhose first argument is not a variable token. - A variable is referenced while no binding for it is in scope.
- A malformed atom appears.
- The 32-bit rules above are violated.
A bare atom such as 5 is a valid whole expression.
Task
Implement evaluate_expression(expr). It returns the integer value of a valid expression, or the string "InvalidExpression" otherwise.
Constraints
0 <= len(expr) <= 10^5- Maximum nesting depth is at most
10^4. - The return value is either an
intor the exact string"InvalidExpression".
Examples
Example 1
Input: evaluate_expression('(sum 1 2)')
Output: 3
Example 2
Input: evaluate_expression('(prod 2 (sum 3 4) -2)')
Output: -28
Example 3
Input: evaluate_expression('(set x 3 (sum x (set x 5 x)))')
Output: 8
Example 4
Input: evaluate_expression('(sum 1)')
Output: 'InvalidExpression'
Hints
Hint 1
Tokenize first with a regular expression that yields '(' , ')' and runs of other non-whitespace characters, so touching parentheses are handled and empty input is easy to detect.
Hint 2
Write a recursive parse function that consumes one expression from a token index and returns its value. Read the operator right after '(', then loop until ')' for sum/prod, and handle set as name, value, body, then ')'.
Hint 3
For scoping, pass a mapping down the recursion. In set, evaluate the value in the current mapping, then evaluate the body in a copy extended with the new name. Be careful about where overflow is checked: every literal, the final sum, and every running product.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the work into three layers.
- Tokenize. One regular expression pulls out
(,)and maximal runs of other non-whitespace characters. This handles parentheses that touch other text and any amount of extra whitespace. No tokens means the input is empty, which is an error. - Recursive descent.
parse(scope)consumes exactly one expression starting at the current token index and returns its value.- Atom. An integer is converted and range-checked. A variable is looked up in
scope, and a missing name is an error. Anything else is malformed. (. Read the operator. Forsumandprod, keep parsing children until), then require at least two values. Asumchecks only its final total. Aprodfolds left to right from 1 and checks every running product. Forset, require the next token to be a variable, parse the value in the current scope, copy the scope with the new binding added, parse the body in that copy, and require the closing). Any other operator is an error.- A stray
)where an expression is expected is an error.
- Atom. An integer is converted and range-checked. A variable is looked up in
- Final check. After the top-level expression, all tokens must have been consumed. Otherwise there is trailing garbage.
Why it is correct
- Each
(is matched by exactly one)that the parsing routine consumes. Missing or extra parentheses end in running out of tokens, meeting an unexpected), or leaving trailing tokens. - The value of a
setis parsed with the outer scope, so(set x 1 (set x (sum x 1) x))reads the outerxwhile computing the inner value and gives 2. - The body gets a copied scope, so the binding disappears when the form closes and inner bindings shadow outer ones without any cleanup.
- Overflow is checked at the specified points: literals, the final
sumtotal, and each runningprodvalue. Python integers are unbounded, so no extra overflow arises in the checks themselves. - Arity and shape rules for
sum,prodandsetare enforced exactly as specified, and every failure path ends in the same"InvalidExpression"result.
Complexity
Let n = len(expr).
- Time: tokenizing is O(n). Each token is handled once. Copying the scope on each
setcosts O(number of visible bindings), which is at most the nesting depth. So the cost is O(n) for typical inputs and O(n * depth) in the worst case. - Space: O(n) for the tokens, plus O(depth) for the recursion and scope copies.
The recursion limit is raised to handle nesting up to 10^4. An iterative version with an explicit frame stack avoids this at the cost of more bookkeeping.
Reference solution
import re
import sys
from typing import Union
_TOKEN = re.compile(r"\(|\)|[^\s()]+")
_INT = re.compile(r"-?[0-9]+\Z")
_VAR = re.compile(r"[a-z][a-z0-9]*\Z")
_MIN_INT = -(1 << 31)
_MAX_INT = (1 << 31) - 1
class _Invalid(Exception):
pass
def evaluate_expression(expr: str) -> Union[int, str]:
try:
tokens = _TOKEN.findall(expr)
if not tokens:
raise _Invalid()
sys.setrecursionlimit(max(sys.getrecursionlimit(), 30000))
pos = 0
def checked(value):
if value < _MIN_INT or value > _MAX_INT:
raise _Invalid()
return value
def parse(scope):
nonlocal pos
if pos >= len(tokens):
raise _Invalid()
token = tokens[pos]
pos += 1
if token == '(':
if pos >= len(tokens):
raise _Invalid()
op = tokens[pos]
pos += 1
if op in ('sum', 'prod'):
values = []
while pos < len(tokens) and tokens[pos] != ')':
values.append(parse(scope))
if pos >= len(tokens) or len(values) < 2:
raise _Invalid()
pos += 1
if op == 'sum':
return checked(sum(values))
result = 1
for value in values:
result = checked(result * value)
return result
if op == 'set':
if pos >= len(tokens) or not _VAR.fullmatch(tokens[pos]):
raise _Invalid()
name = tokens[pos]
pos += 1
value = parse(scope)
child = scope.copy()
child[name] = value
result = parse(child)
if pos >= len(tokens) or tokens[pos] != ')':
raise _Invalid()
pos += 1
return result
raise _Invalid()
if token == ')':
raise _Invalid()
if _INT.fullmatch(token):
return checked(int(token))
if _VAR.fullmatch(token):
if token not in scope:
raise _Invalid()
return scope[token]
raise _Invalid()
result = parse({})
if pos != len(tokens):
raise _Invalid()
return result
except (_Invalid, RecursionError, ValueError, OverflowError):
return "InvalidExpression"