Files
agent-orchestrator-benchmark/calculators/builder-adversary-lean/run-04/calc/evaluator.py

38 lines
1.1 KiB
Python

from calc.parser import Num, BinOp, Unary
class EvalError(Exception):
pass
def evaluate(node):
"""Walk the AST returned by parse() and return int | float."""
if isinstance(node, Num):
return node.value
if isinstance(node, Unary):
if node.op == '-':
return -evaluate(node.operand)
raise EvalError(f"unknown unary op {node.op!r}")
if isinstance(node, BinOp):
left = evaluate(node.left)
right = evaluate(node.right)
if node.op == '+':
return left + right
if node.op == '-':
return left - right
if node.op == '*':
return left * right
if node.op == '/':
if right == 0:
raise EvalError("division by zero")
return left / right
raise EvalError(f"unknown binary op {node.op!r}")
raise EvalError(f"unknown AST node type {type(node).__name__!r}")
def format_result(value) -> str:
"""Format a numeric result: whole-valued floats print without '.0', others as-is."""
if isinstance(value, float) and value == int(value):
return str(int(value))
return str(value)