artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
37
calculators/builder-solo/run-01/calc/evaluator.py
Normal file
37
calculators/builder-solo/run-01/calc/evaluator.py
Normal file
@ -0,0 +1,37 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from calc.parser import BinOp, Node, Num, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node) -> int | float:
|
||||
"""Walk an AST and return its numeric value.
|
||||
|
||||
Result type rule: integer arithmetic stays int; true division always
|
||||
produces a float (callers display whole-valued floats without '.0').
|
||||
"""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
val = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return -val
|
||||
raise EvalError(f"unknown unary operator: {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 operator: {node.op!r}")
|
||||
raise EvalError(f"unknown node type: {type(node)!r}")
|
||||
Reference in New Issue
Block a user