artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
@ -0,0 +1,42 @@
|
||||
from calc.parser import Num, BinOp, Unary, parse
|
||||
from calc.lexer import tokenize
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node) -> int | float:
|
||||
"""Walk the AST and return an int or float.
|
||||
|
||||
Result type rule: if the result is a whole number (no fractional part),
|
||||
return int; otherwise return float.
|
||||
"""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
val = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return _coerce(-val)
|
||||
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 _coerce(left + right)
|
||||
if node.op == '-':
|
||||
return _coerce(left - right)
|
||||
if node.op == '*':
|
||||
return _coerce(left * right)
|
||||
if node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
return _coerce(left / right)
|
||||
raise EvalError(f"unknown binary op {node.op!r}")
|
||||
raise EvalError(f"unknown AST node {type(node).__name__!r}")
|
||||
|
||||
|
||||
def _coerce(val: int | float) -> int | float:
|
||||
if isinstance(val, float) and val == int(val):
|
||||
return int(val)
|
||||
return val
|
||||
Reference in New Issue
Block a user