def greatest_common_factor(a,b): """Returns: Greatest common factor of a and b. Precondition: a and b are integers.""" while a != b: if a > b: a -= b else: b -= a return a def lowest_common_multiple(a, b): """Compute the lowest common multiple of a and b""" "Precondition: a and b are integers.""" return a * b / greatest_common_factor(a, b) class Fraction(object): """ Class to hold a fraction. numerator [int] denominator [int > 0] """ def __init__(self, numerator, denominator): """ Initialize fraction Precondition: numerator [int] denominator [int > 0] """ self.numerator = numerator self.denominator = denominator def __add__(self, other): """ slightly less lazy way to add fractions """ lcm = lowest_common_multiple(self.denominator, other.denominator) bottom = lcm top = (lcm / self.denominator) * self.numerator + (lcm / other.denominator) * other.numerator return Fraction(top, bottom) def __str__(self): return str(self.numerator) + "/" + str(self.denominator) def __eq__(self, other): self.reduce() other.reduce() return self.numerator == other.numerator and self.denominator == other.denominator def reduce(self): if self.numerator == 0: return gcf = greatest_common_factor(self.numerator, self.denominator) self.numerator /= gcf self.denominator /= gcf class MixedNumber(Fraction): """ Class to hold a fraction. whole_number [int] numerator [int] denominator [int > 0] """ def __init__(self, whole_number, numerator, denominator): """ Initialize mixed number Precondition: whole_number [int] numerator [int] denominator [int > 0] """ Fraction.__init__(self, numerator, denominator) self.whole_number = whole_number def __str__(self): return str(self.whole_number) + " " + Fraction.__str__(self) def __add__(self, other): """ add mixed numbers precondition: fractions are proper """ assert isinstance(other, Fraction) new_fraction = Fraction.__add__(self, other) new_whole_number = self.whole_number if isinstance(other,MixedNumber): new_whole_number = new_whole_number + other.whole_number if new_fraction.numerator >= new_fraction.denominator: new_fraction.numerator = new_fraction.numerator - new_fraction.denominator new_whole_number = new_whole_number + 1 return MixedNumber(new_whole_number, new_fraction.numerator, new_fraction.denominator)