Neural Mastery
← Practice
Abstract Syntax Tree (AST) Evaluatorhard

Abstract Syntax Tree (AST) Evaluator

hard Python for AI 20–25 min

NumPy allowed · plain Python earns 10 bonus points

Evaluate recursive expression abstract syntax trees with variable environment scoping.

Related Skills

Task

Implement evaluate_ast(node, env): recursively evaluate an expression AST. Nodes are: numeric constants {"type": "num", "val": float}, variable references {"type": "var", "name": str} (looked up in env), and binary operators {"type": "binop", "op": "+", "left": ..., "right": ...}. Return the evaluated float result.

Function Signature

evaluate_ast(node: dict, env: dict[str, float]) -> float

Examples

Example 1: Simple Addition with Variable
Input: node = {'type': 'binop', 'op': '+', 'left': {'type': 'var', 'name': 'x'}, 'right': {'type': 'num', 'val': 3}} env = {'x': 2}
Output: 5
Example 2: Multiplication with Float
Input: node = {'type': 'binop', 'op': '*', 'left': {'type': 'num', 'val': 4}, 'right': {'type': 'var', 'name': 'y'}} env = {'y': 2.5}
Output: 10
Example 3: Deeply Nested Expressions
Input: node = {'type': 'binop', 'op': '-', 'left': {'type': 'binop', 'op': '*', 'left': {'type': 'num', 'val': 10}, 'right': {'type': 'num', 'val': 2}}, 'right': {'type': 'binop', 'op': '/', 'left': {'type': 'num', 'val': 8}, 'right': {'type': 'num', 'val': 2}}} env = {}
Output: 16

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Supports standard operators: +, -, *, /.
  • Recursive traversal handling arbitrarily deep expression trees.
Python3Saved ✓
def evaluate_ast(node: dict, env: dict[str, float]) -> float:
"""Recursively evaluate an Abstract Syntax Tree (AST) node using environment dict env.
Nodes:
- {'type': 'num', 'val': float}
- {'type': 'var', 'name': str}
- {'type': 'binop', 'op': '+' | '-' | '*' | '/', 'left': node, 'right': node}"""
# Your implementation here
pass

Case 1: Simple Addition with Variable
Input: node = {'type': 'binop', 'op': '+', 'left': {'type': 'var', 'name': 'x'}, 'right': {'type': 'num', 'val': 3}} env = {'x': 2}
Expected: 5
Case 2: Multiplication with Float
Input: node = {'type': 'binop', 'op': '*', 'left': {'type': 'num', 'val': 4}, 'right': {'type': 'var', 'name': 'y'}} env = {'y': 2.5}
Expected: 10
Case 3: Deeply Nested Expressions
Input: node = {'type': 'binop', 'op': '-', 'left': {'type': 'binop', 'op': '*', 'left': {'type': 'num', 'val': 10}, 'right': {'type': 'num', 'val': 2}}, 'right': {'type': 'binop', 'op': '/', 'left': {'type': 'num', 'val': 8}, 'right': {'type': 'num', 'val': 2}}} env = {}
Expected: 16