class Fraction: """ Each Fraction object consists of a numerator and a denominator. Fractions are reduced by dividing the numerator and denominator by their greatest common divisor (GCD). """ def __init__(self, numerator, denominator = 1): """ Construct a fraction and reduce it. @param numerator the fraction's numerator. @param denominator the fraction's denominator. """ if denominator == 0: raise ZeroDivisionError('Denominator cannot be 0.') if numerator == 0: self._numerator = 0 self._denominator = 1 else: # Determine fraction's sign: # 1 if positive, -1 if negative if ( ((numerator < 0) and (denominator >= 0)) or ((numerator >= 0) and (denominator < 0)) ): sign = -1 else: sign = 1 # Greatest common divisor. gcd = self._gcd(numerator, denominator) # Reduce the fraction. self._numerator = sign*abs(numerator)//gcd self._denominator = abs(denominator)//gcd def _gcd(self, a, b): """ Private method! Calculate the greatest common divisor of a and b. @param a @param b @return the GCD of a and b. """ while b: a, b = b, a%b return a def add(self, other): """ Return the Fraction value of self + other. """ num = (self._numerator * other._denominator + self._denominator * other._numerator) den = self._denominator * other._denominator return Fraction(num, den) def __add__(self, other): """ Return the Fraction value of self + other. """ return self.add(other) def __sub__(self, other): """ Return the Fraction value of self - other. """ num = (self._numerator * other._denominator - self._denominator * other._numerator) den = self._denominator * other._denominator return Fraction(num, den) def __mul__(self, other): """ Return the Fraction value of self * other. """ num = self._numerator * other._numerator den = self._denominator * other._denominator return Fraction(num, den) def __truediv__(self, other): """ Return the Fraction value of self / other. """ num = self._numerator * other._denominator den = self._denominator * other._numerator return Fraction(num, den) def __repr__(self): ''' @return the string representation of a Fraction object. ''' return (f'{self._numerator}/{self._denominator}')