""" A Rational class, closely followed the example by John W. Shipman of New Mexico Tech http://infohost.nmt.edu/tcc/help/lang/python/examples/rational/rational.pdf Xiannong Meng CSCI 204 Fall 2017 """ class Rational: def __init__(self, a = 0, b = 1): """ Constructor """ if b == 0: raise ZeroDivisionError elif isinstance(a, int) == False or isinstance(b, int) == False: raise ValueError else: g = self.gcd ( a, b ) self.n = a // g self.d = b // g def __str__(self): """ Return a string rep """ return str(self.n) + ' / ' + str(self.d) def gcd(self, a, b): """ Return the greastest common divisor of a and b """ if b == 0: return a else: return self.gcd(b, a % b) def __add__(self, other): """ Add two rationals """ return Rational(self.n * other.d + other.n*self.d, \ self.d * other.d) def __sub__(self, other): """ Subtract other from self """ return Rational(self.n * other.d - other.n*self.d, \ self.d * other.d) def __mul__(self, other): """ Multiply self with other """ return Rational(self.n * other.n, self.d * other.d) def __floordiv__(self, other): """ Divide self by other """ ''' According to the Stackoverflow post, __floordiv__ is // and __truediv__ is / https://stackoverflow.com/questions/21859440/error-when-trying-to-overload-an-operator ''' return Rational(self.n * other.d, self.d * other.n) def __eq__(self, other): """ Compare if two Rationals are equal Precondition: 'other' must be a Rational that has been reduced. """ return self.n == other.n and self.d == other.d def is_zero(self): """ Returns True if this Rational is zero (0/n) """ return self.n == 0 def __gt__(self, other): """ Returns True if self > other """ return self.n * other.d > self.d * other.n def __ge__(self, other): """ Returns True if self >= other """ return self.n * other.d >= self.d * other.n def __lt__(self, other): """ Returns True if self < other """ return self.n * other.d < self.d * other.n def __le__(self, other): """ Returns True if self <= other """ return self.n * other.d <= self.d * other.n