解答: 分数的加减乘除操作,结合欧几里得消除公约数。在 初始化方法中,再加入对数字溢出的判断更合理,也即1.2.17题目。
class Rational:
def __init__(self, numerator:int, denominator:int):
super().__init__()
if denominator == 0:
raise ValueError('denominator can not be zero')
gcd = self._gcd(numerator, denominator)
self.numerator = numerator//gcd
self.denominator = denominator//gcd
def plus(self, b):
return Rational(self.numerator*b.denominator+b.numerator*self.denominator, self.denominator*b.denominator)
def minus(self, b):
return Rational(self.numerator*b.denominator-b.numerator*self.denominator, self.denominator*b.denominator)
def times(self, b):
return Rational(self.numerator*b.numerator, self.denominator*b.denominator)
def divides(self, b):
# a1/b1 / a2/b2 = a1/b1 * b2/a2
return Rational(self.numerator*b.denominator, self.denominator*b.numerator)
def equals(self, b):
return self.numerator == b.numerator and self.denominator == b.denominator
def _gcd(self,p, q):
if q == 0:
return p
r = p % q
return self._gcd(q, r)