artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
from calc.parser import Num, BinOp, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(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")
|
||||
return left / right
|
||||
raise EvalError(f"unknown binary op: {node.op!r}")
|
||||
raise EvalError(f"unknown node type: {type(node).__name__}")
|
||||
|
||||
|
||||
def format_result(value) -> str:
|
||||
"""Whole-valued results print without .0; non-whole as float."""
|
||||
if isinstance(value, float) and value == int(value):
|
||||
return str(int(value))
|
||||
return str(value)
|
||||
Reference in New Issue
Block a user