From 1347c30b9270ba78c07096e4d5a1aa9cba6c0b18 Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Sun, 26 Sep 2021 08:58:42 +0200 Subject: [PATCH] Feat: simplified version for Fraction and MOFraction --- mapytex/calculus/API/tokens/number.py | 23 +++++++++++++++++++ mapytex/calculus/core/MO/fraction.py | 32 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/mapytex/calculus/API/tokens/number.py b/mapytex/calculus/API/tokens/number.py index 7924b9a..266e124 100644 --- a/mapytex/calculus/API/tokens/number.py +++ b/mapytex/calculus/API/tokens/number.py @@ -271,6 +271,29 @@ class Fraction(Token): """ return Decimal(self._mo._value) + def simplified(self): + """ Get the irreductible version of self + + :example: + >>> f = Fraction("3/4") + >>> f.simplified() + + >>> f = Fraction("12/9") + >>> f.simplified() + + >>> f = Fraction("12/4") + >>> f.simplified() + + + """ + simplified = self._mo.simplified() + + if isinstance(simplified, MOnumber): + return Integer(simplified) + + return Fraction(simplified) + + # ----------------------------- diff --git a/mapytex/calculus/core/MO/fraction.py b/mapytex/calculus/core/MO/fraction.py index 133b1b1..de0e96f 100644 --- a/mapytex/calculus/core/MO/fraction.py +++ b/mapytex/calculus/core/MO/fraction.py @@ -10,6 +10,7 @@ from mapytex.calculus.core.tree import Tree from .mo import Molecule, MO from .atoms import MOnumber from decimal import Decimal +from ..arithmetic import gcd __all__ = ["MOFraction"] @@ -95,6 +96,37 @@ class MOFraction(Molecule): else: raise NotImplementedError + def simplified(self): + """ Simplified version of self + + :examplex + >>> f = MOFraction(2, 3) + >>> f + + >>> f.simplified() + + >>> f = MOFraction(2, 6) + >>> f + + >>> f.simplified() + + >>> f = MOFraction(32, 24) + >>> f.simplified() + + >>> f = MOFraction(32, 8) + >>> f.simplified() + + """ + frac_gcd = gcd(self.numerator._value, self.denominator._value) + new_num = self.numerator._value / frac_gcd + new_denom = self.denominator._value / frac_gcd + + if new_denom == 1: + return MOnumber(new_num) + + return MOFraction(new_num, new_denom) + + # ----------------------------- # Reglages pour 'vim'