27 lines
725 B
Python
27 lines
725 B
Python
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):
|
|
return -evaluate(node.operand)
|
|
if isinstance(node, BinOp):
|
|
left = evaluate(node.left)
|
|
right = evaluate(node.right)
|
|
if node.op == 'PLUS':
|
|
return left + right
|
|
if node.op == 'MINUS':
|
|
return left - right
|
|
if node.op == 'STAR':
|
|
return left * right
|
|
if node.op == 'SLASH':
|
|
if right == 0:
|
|
raise EvalError("division by zero")
|
|
return left / right
|
|
raise EvalError(f"unknown node: {node!r}")
|