artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
40
calculators/builder-solo/run-04/calc/evaluator.py
Normal file
40
calculators/builder-solo/run-04/calc/evaluator.py
Normal file
@ -0,0 +1,40 @@
|
||||
"""AST evaluator for calc expressions.
|
||||
|
||||
evaluate(node) -> int | float
|
||||
|
||||
Result-type rule:
|
||||
- Whole-valued results (including float 2.0) are returned/displayed as int.
|
||||
- Non-whole results are returned as float.
|
||||
Division by zero raises EvalError, not a bare ZeroDivisionError.
|
||||
"""
|
||||
|
||||
from calc.parser import Num, BinOp, Unary, Node
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node) -> "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")
|
||||
result = left / right
|
||||
return int(result) if result == int(result) else result
|
||||
raise EvalError(f"unknown binary op {node.op!r}")
|
||||
raise EvalError(f"unknown node type {type(node).__name__}")
|
||||
Reference in New Issue
Block a user