Testimonials

Sample IT Assignment Help !
 In many ways it would be better if all fractions were maintained in lowest terms right from the start. Modify the constructor for the Fraction Class so that GCD is used to reduce the fraction immediately. Notice that this means the __add__ function no longer needs to reduce. Make the necessary modifications.
 In the definition of fractions we assumed that negative fractions have a negative numerator and a positive denominator. Using a negative denominator would cause the __cmp__ function to give incorrect results. In general, this is an unnecessary constraint. Modify the constructor to allow the user to pass a negative denominator so that the __cmp__ function continues to work properly.
 Complete the implementation of the Fraction Class by overriding the methods for multiplication, subtraction, and division.
Solution
class Fraction:
def __init__(self,top,bottom):
if(bottom<0)
top=top*(1)
common = gcd(top,bottom)
self.num = top/common
self.den = bottom/common
def __str__(self):
return str(self.num)+"/"+str(self.den)
def show(self):
print self.num,"/",self.den
def __add__(self,otherfraction):
newnum = self.num * otherfraction.den + \
self.den * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum,newden)
def __subtract__(self,otherfraction):
newnum = self.num * otherfraction.den  \
self.den * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum,newden)
def __multiply__(self,otherfraction):
newnum = self.num * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum,newden)
def __divide__(self,otherfraction):
newnum = self.num * otherfraction.den
newden = self.den * otherfraction.num
return Fraction(newnum,newden)
def __cmp__(self,otherfraction):
num1 = self.num*otherfraction.den
num2 = self.den*otherfraction.num
if num1 < num2:
return 1
else:
if num1 == num2:
return 0
else:
return 1
#Assume that m and n are greater than zero
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n

