def _simplify(self): if not self: return coeffs = self._numerator.coefficients + self._denominator.coefficients if len(coeffs) > 1: gcd_ = gcd(*coeffs) self._numerator /= gcd_ self._denominator /= gcd_ if not self._numerator % self._denominator: num = self._numerator // self._denominator if num.is_constant() and num: num = num.coefficients[0] self._numerator = Polynomial.from_iterable([[num.numerator, {}]]) self._denominator = Polynomial.from_iterable([[num.denominator, {}]]) else: self._numerator = num self._denominator = Polynomial("1") elif not self._denominator % self._numerator and\ not self._numerator.is_constant(): den = self._denominator // self._numerator self._denominator = den self._numerator = Polynomial("1")
def test_gcd(self): self.assertEqual(gcd(0, 0), 1) self.assertEqual(gcd(5, 0), 5) self.assertEqual(gcd(0, 5), 5) self.assertEqual(gcd(5, 5), 5) self.assertEqual(gcd(5, 1), 1) self.assertEqual(gcd(5, 0), 5) self.assertEqual(gcd(33, 121), 11) self.assertEqual(gcd(256, 160), 32) self.assertEqual(gcd(256, -160), 32) self.assertEqual(gcd(-256, 160), 32) self.assertEqual(gcd(-256, -160), 32) self.assertEqual(gcd(Polynomial("x2 - 2x + 1"), Polynomial("x2 - 3x + 2")), Polynomial("x - 1")) self.assertEqual(gcd(Polynomial("120x2y4z7t"), Polynomial("24xy5zhg")), Polynomial("24xy4z")) self.assertEqual(gcd(4, Polynomial("2x2 - 2x + 2")), 2) self.assertEqual(gcd(Polynomial("4"), Polynomial("2x2 - 2x + 2")), 2) self.assertEqual(gcd(fractions.Fraction(3, 2), fractions.Fraction(21, 6)), fractions.Fraction(1, 2)) self.assertEqual(gcd(1.2, 4.6), fractions.Fraction(1, 5)) self.assertEqual(gcd(1j, 2), 1) self.assertEqual(gcd(fractions.Fraction(4, 2), 6), 2) self.assertEqual(gcd(2.0, 6), 2) self.assertEqual(gcd(-2.0, 6), 2) self.assertEqual(gcd(fractions.Fraction(4), Polynomial("2x2 - 2x + 2")), 2) self.assertEqual(gcd(8j, 12j), 4j) self.assertEqual(gcd(8j, 0), 8j) self.assertEqual(gcd(Polynomial("x - 2"), Polynomial("x")), Polynomial("1")) self.assertEqual(gcd(30, 24, 54, 36), 6) self.assertEqual(gcd(*(2 * x for x in range_(10))), 2) self.assertEqual(gcd(Polynomial("x - 2") * "x - 1", Polynomial("x - 1") ** 2, Polynomial("y") * "x - 1", Polynomial("x - 1")), "x - 1") #self.assertEqual(gcd(Polynomial("2x - 4") * "x - 1", # Polynomial("x - 1") ** 2 * 6, # Polynomial("4y") * "x", # Polynomial("2x - 2"), # -2, # fractions.Fraction(16, 4), # 8.0, # 16), 2) self.assertRaises(TypeError, gcd, "3", 6) self.assertRaises(TypeError, gcd, 3, "6") self.assertRaises(TypeError, gcd, [3], "6") self.assertRaises(TypeError, gcd, 3, 6, []) self.assertRaises(TypeError, gcd, 3, 6, 9, 18, "") self.assertRaises(TypeError, gcd, 3) self.assertRaises(TypeError, gcd) self.assertRaises(TypeError, gcd, 3, 6, pippo=3)
def greatest_common_divisor(self): if not self: return Polynomial("1") elif len(self) == 1: return Polynomial.from_iterable([self._monomials[0]]) return gcd(*(Polynomial.from_iterable([m]) for m in self._monomials))