artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
@ -0,0 +1,44 @@
|
||||
"""Evaluator: walks an AST (from calc.parser) and returns int | float.
|
||||
|
||||
Result-type rule: if the result is whole-valued (no fractional part), return int;
|
||||
otherwise return float. This means 4/2 → 2 (int) and 7/2 → 3.5 (float).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from calc.parser import Num, BinOp, Unary, Node
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _normalize(v: int | float) -> int | float:
|
||||
if isinstance(v, float) and v == int(v):
|
||||
return int(v)
|
||||
return v
|
||||
|
||||
|
||||
def evaluate(node: Node) -> int | float:
|
||||
if isinstance(node, Num):
|
||||
return _normalize(node.value)
|
||||
if isinstance(node, Unary):
|
||||
val = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return _normalize(-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 == '+':
|
||||
result = left + right
|
||||
elif node.op == '-':
|
||||
result = left - right
|
||||
elif node.op == '*':
|
||||
result = left * right
|
||||
elif node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
result = left / right
|
||||
else:
|
||||
raise EvalError(f"unknown operator: {node.op!r}")
|
||||
return _normalize(result)
|
||||
raise EvalError(f"unknown node type: {type(node).__name__}")
|
||||
Reference in New Issue
Block a user