from math import * def gcd(a,b): u, v = a, b counter2=0; while v != 0: r = u % v #print "The remainder is", r u = v v = r counter2 +=1 return u class Fraction: def __init__(self,num=0,denom=1): if denom==0: # fraction is undefined self._n=0 self._d=0 else : factor = gcd(abs(num),abs(denom)) if denom < 0: factor=-factor self._n=num/factor self._d=denom/factor def __str__(self): if self._d == 0: return 'Undefined' elif self._d == 1 : return str(self._n) else: return str(self._n) + '/' + str(self._d) def __add__(self,other): # Addition of two fractions return Fraction(self._n*other._d+other._n*self._d,self._d*other._d) def __sub__(self,other): # Subtraction of two fractions return Fraction(self._n*other._d-other._n*self._d,self._d*other._d) def __mul__(self,other): # Multiplication of two fractions return Fraction(self._n*other._n,self._d*other._d) def __div__(self,other): # division of two fractions self/other return Fraction(self._n*other._d,self._d*other._n) def __neg__(self): # negation of a fraction return Fraction(-self._n,self._d) def n_invert(self): # negative reciprocal of a fraction return Fraction(self._d,self._n).__neg__() #return -Fraction(self._d,self._n) # conversion of a fraction to a mixed number # so far if a user tries to convert a proper fraction to a mixed number, # the warning is displayed, but the mixed number is still created, # with 0 as the whole part (quotient) def fraction2mixed(self): if self._n < self._d: print "Warning: you tried to convert a proper fraction to a mixed number!" print "The mixed number was created, but its whole part (quotient) is 0" return MixedNumber(0,self._n,self._d) else: return MixedNumber(self._n//self._d,self._n%self._d,self._d) class MixedNumber(Fraction): def __init__(self,quotient=0,num=0,denom=1): # initially, by default, we have 0 0/1 self._q=quotient if num < denom: # fractional part if a proper fraction Fraction.__init__(self,num,denom) else: # takes care of improper fraction as a fractional part # of the mixed number self._q += num // denom r=num%denom Fraction.__init__(self,r,denom) def __str__(self): if self._d == 0: # if denominator is 0, the mixed number is undefined return 'Undefined' elif self._n == 0: # if the numerator is 0 if self._q == 0: # and the whole part(quotient) is 0 return str(0) else: # and the whole part (quotient) is not 0 return str(self._q) else: str1=' ' + str(self._n) + '\n' str2=str(self._q)+' -\n' str3=' ' + str(self._d) return str1+str2+str3+'\n' #return str(self._q) + ' ' + str(self._n) + ' ' + str(self._d) # conversion of a mixed number to improper fraction def mixed2fraction(self): return Fraction(self._q*self._d+self._n,self._d) def main(): m1=MixedNumber(2,5,4) m2=MixedNumber(1,2,3) print m1 print m2 f1=m1.mixed2fraction() print f1 f2=m2.mixed2fraction() print f2 f3=Fraction(14,23) print f3 m3=f3.fraction2mixed() print m3 main()