artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
@ -0,0 +1,43 @@
|
||||
from __future__ import annotations
|
||||
from calc.parser import Num, BinOp, Unary, Node
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node) -> int | float:
|
||||
"""Walk the AST and return the numeric result."""
|
||||
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}")
|
||||
|
||||
|
||||
def fmt_result(v: int | float) -> str:
|
||||
"""Format a result for display.
|
||||
|
||||
Rule: whole-valued floats (e.g. 2.0 from 4/2) print without a trailing .0;
|
||||
non-whole floats print normally; integers print as integers.
|
||||
"""
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
return str(int(v))
|
||||
return str(v)
|
||||
Reference in New Issue
Block a user