calculator: use commonly defined operations

This commit is contained in:
Bruno BELANYI 2019-11-30 16:27:45 +01:00
parent f103adddac
commit 2490e1a5bd
4 changed files with 57 additions and 4 deletions

View file

@ -1,2 +1,3 @@
import calculator.core # isort:skip
import calculator.ast
import calculator.eval

View file

@ -0,0 +1 @@
import calculator.core.operations

View file

@ -0,0 +1,35 @@
def plus(x: int, y: int) -> int:
return x + y
def minus(x: int, y: int) -> int:
return x - y
def times(x: int, y: int) -> int:
return x * y
def int_div(x: int, y: int) -> int:
return x // y
def pow(x: int, y: int) -> int:
return x ** y
def identity(x: int) -> int:
return x
def negate(x: int) -> int:
return -x
STR_TO_BIN = {
"+": plus,
"-": minus,
"*": times,
"/": int_div,
"^": pow,
}

View file

@ -1,5 +1,6 @@
import pytest
from calculator.ast import BinOp, Constant, UnaryOp
from calculator.core import operations
from .evaluator import Evaluator
@ -15,20 +16,35 @@ def test_evaluate_constant(vis):
def test_evaluate_unaryop_identity(vis):
op = UnaryOp(lambda x: x, Constant(42))
op = UnaryOp(operations.identity, Constant(42))
assert vis.visit_and_get_value(op) == 42
def test_evaluate_unaryop_negate(vis):
op = UnaryOp(lambda x: -x, Constant(-42))
op = UnaryOp(operations.negate, Constant(-42))
assert vis.visit_and_get_value(op) == 42
def test_evaluate_binop_plus(vis):
op = BinOp(lambda x, y: x + y, Constant(12), Constant(27))
op = BinOp(operations.plus, Constant(12), Constant(27))
assert vis.visit_and_get_value(op) == 39
def test_evaluate_binop_minus(vis):
op = BinOp(lambda x, y: x - y, Constant(42), Constant(51))
op = BinOp(operations.minus, Constant(42), Constant(51))
assert vis.visit_and_get_value(op) == -9
def test_evaluate_binop_times(vis):
op = BinOp(operations.times, Constant(6), Constant(9))
assert vis.visit_and_get_value(op) == 54
def test_evaluate_binop_int_div(vis):
op = BinOp(operations.int_div, Constant(5), Constant(2))
assert vis.visit_and_get_value(op) == 2
def test_evaluate_binop_pow(vis):
op = BinOp(operations.pow, Constant(3), Constant(4))
assert vis.visit_and_get_value(op) == 81