From 92af420efec4ca630fa3777cdf8bf3f9d541d13e Mon Sep 17 00:00:00 2001 From: Florentin Labelle <florentin.labelle@student-cs.fr> Date: Sun, 9 Oct 2022 19:12:22 +0200 Subject: [PATCH] integer calculator instead --- calculator/calculator.py | 4 ++-- calculator/expression.py | 2 +- calculator/test_calculator.py | 16 ++++++++-------- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/calculator/calculator.py b/calculator/calculator.py index 980a8c3..1847cd0 100644 --- a/calculator/calculator.py +++ b/calculator/calculator.py @@ -28,8 +28,8 @@ class Calculator: tokens.append(self.operators[token]) else: try: - term = float(token) - tokens.append(term) + if int(token) == float(token): + tokens.append(int(token)) except ValueError as exc: raise ValueError(f"Invalid token {token}") from exc return tokens diff --git a/calculator/expression.py b/calculator/expression.py index b46f44a..d796722 100644 --- a/calculator/expression.py +++ b/calculator/expression.py @@ -5,7 +5,7 @@ from typing import Union from calculator.operators import Operator -Term: type = float +Term: type = int Token: type = Union[Operator, Term] diff --git a/calculator/test_calculator.py b/calculator/test_calculator.py index 8f56766..a7a07e2 100644 --- a/calculator/test_calculator.py +++ b/calculator/test_calculator.py @@ -25,12 +25,12 @@ def test_tokenizer(setup): Test the tokenizer. """ plus, minus, times, divide, calc = setup - assert calc.tokenize("1 + 2") == [1.0, plus, 2.0] - assert calc.tokenize("1 + 2 * 3") == [1.0, plus, 2.0, times, 3.0] + assert calc.tokenize("1 + 2") == [1, plus, 2] + assert calc.tokenize("1 + 2 * 3") == [1, plus, 2, times, 3] assert calc.tokenize( - "1 + 2 * 3 / 4") == [1.0, plus, 2.0, times, 3.0, divide, 4.0] + "1 + 2 * 3 / 4") == [1, plus, 2, times, 3, divide, 4] assert calc.tokenize( - "1 + 2 * 3 / 4 - 5") == [1.0, plus, 2.0, times, 3.0, divide, 4.0, minus, 5.0] + "1 + 2 * 3 / 4 - 5") == [1, plus, 2, times, 3, divide, 4, minus, 5] def test_parser(setup): @@ -38,13 +38,13 @@ def test_parser(setup): Test the parser. """ _, _, _, _, calc = setup - assert repr(calc.parse(calc.tokenize("1 + 2"))) == '(1.0 + 2.0)' + assert repr(calc.parse(calc.tokenize("1 + 2"))) == '(1 + 2)' assert repr(calc.parse(calc.tokenize("1 + 2 * 3")) - ) == '(1.0 + (2.0 * 3.0))' + ) == '(1 + (2 * 3))' assert repr(calc.parse(calc.tokenize( - "1 + 2 * 3 / 4"))) == '(1.0 + ((2.0 * 3.0) / 4.0))' + "1 + 2 * 3 / 4"))) == '(1 + ((2 * 3) / 4))' assert repr(calc.parse(calc.tokenize( - "1 + 2 * 3 / 4 - 5"))) == '((1.0 + ((2.0 * 3.0) / 4.0)) - 5.0)' + "1 + 2 * 3 / 4 - 5"))) == '((1 + ((2 * 3) / 4)) - 5)' def test_evaluation(setup): -- GitLab