Next / Previous / Contents / Shipman's homepage

3.11. Rational.mixed(): Display as a mixed fraction

This method is used to convert a rational number (which may be an improper fraction) to a “mixed fraction”. The general form of a mixed fraction is a phrase of the form “w and n/d” For example, the improper fraction 22/7 is equivalent to the mixed fraction “3 and 1/7”.

The result is returned as a string. There are three cases:

First we find the whole-number part and the numerator of the fractional part (the denominator of the fractional part will be the same as the denominator of the original rational). Python conveniently provides the divmod() function, which provides both the quotient and the remainder.

rational.py
    def mixed ( self ):
        """Render self as a mixed fraction in string form.
        """
        #-- 1 --
        # [ whole  :=  self.n / self.d, truncated
        #   n2  :=  self.n % self.d ]
        whole, n2  =  divmod ( self.n, self.d )

Then we separate the three cases.

rational.py
        #-- 2 --
        # [ if self.d == 1 ->
        #     return str(self.n)
        #   else if whole == zero ->
        #     return str(n2)+"/"+str(self.d)
        #   else ->
        #     return str(whole)+" and "+str(n2)+"/"+str(self.d) ]
        if  self.d == 1:
            return str(self.n)
        elif whole == 0:
            return "%s/%s" % (n2, self.d)
        else:
            return "%s and %s/%s" % (whole, n2, self.d)