Parse Lisp Expression - Problem
Imagine you're building an interpreter for a simplified Lisp programming language! Your task is to parse and evaluate mathematical expressions written in a special syntax.
You'll encounter four types of expressions:
- Integers: Simple numbers like
42or-15 - Variables: Named values like
xorcount1 - Add expressions:
(add 3 5)evaluates to8 - Mult expressions:
(mult 4 6)evaluates to24 - Let expressions:
(let x 2 y 3 (add x y))assignsx=2,y=3, then evaluates(add x y)to get5
The tricky part? Variable scoping! When variables are redefined in nested expressions, the innermost definition takes precedence, just like in real programming languages.
Example: (let x 1 (let x 2 x)) returns 2 because the inner x shadows the outer one.
Input & Output
example_1.py โ Simple Addition
$
Input:
expression = "(add 1 2)"
โบ
Output:
3
๐ก Note:
Basic addition operation: 1 + 2 = 3. The add operator takes two operands and returns their sum.
example_2.py โ Let Expression with Variable
$
Input:
expression = "(let x 2 (mult x 5))"
โบ
Output:
10
๐ก Note:
First assigns x = 2, then evaluates (mult x 5) = (mult 2 5) = 10. The let expression creates a local scope where x has value 2.
example_3.py โ Nested Scopes with Variable Shadowing
$
Input:
expression = "(let x 1 (let x 2 x))"
โบ
Output:
2
๐ก Note:
The outer let assigns x = 1, but the inner let reassigns x = 2. The final expression 'x' refers to the inner scope's value of 2, demonstrating variable shadowing.
Constraints
- 1 โค expression.length โค 2000
- The given expression is guaranteed to be a legal Lisp expression
- The final answer will fit in a 32-bit integer
- Variable names consist of lowercase letters and digits only
-
Protected keywords:
"add","let","mult"will never be used as variable names
Visualization
Tap to expand
Understanding the Visualization
1
Tokenize the Expression
Break the expression string into meaningful tokens: parentheses, operators, variables, and numbers
2
Create Scope Hierarchy
Each opening parenthesis creates a new scope box that can inherit variables from outer boxes
3
Process Let Assignments
For let expressions, assign variables to the current scope box, shadowing any outer variables with the same name
4
Evaluate Operations
For add/mult operations, recursively evaluate operands using the current variable scope
5
Return and Clean Up
Return the computed value and automatically clean up the current scope as the recursion unwinds
Key Takeaway
๐ฏ Key Insight: Use a recursive approach where each function call manages its own variable scope through hash maps. This naturally handles the nested scoping rules of Lisp while maintaining O(n) time complexity through efficient tokenization and O(1) variable lookups.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code