#ShowFract.py """ Illustrate a class that supports various operations of fractions. Shows how to overload "+" and "*" """ def gcd(a,b): """ Returns the greatest common divisor of a and b PreC: a and b are ints and b is positive """ a = abs(a) b = abs(b) r = a%b while r>0: a = b b = r r = a%b return b class Fraction: """ A class that supports operations with fractions. Attributes: num: the numerator [int] den: the denominator [positive int] num and den have no common factors larger than 1. """ def __init__(self,p,q=1): """ Returns a Fraction Object that represents p/q PreC p and q are ints and q is nonzero """ d = gcd(p,q) self.num = p/d self.den = q/d if self.den<0: # Make sure the denominator is positive self.den = -self.den self.num = -self.num def __str__(self): """ Pretty prints self """ return '%1d/%1d' % (self.num,self.den) def __add__(self,f): """ Returns a Fraction that is the sum of self and f PreC: f is either an int or a Fraction """ if isinstance(f,Fraction): # f is a fraction N = self.num*f.den + self.den*f.num D = self.den*f.den else: # f is an int N = self.num + self.den*f D = self.den return Fraction(N,D) def __mul__(self,f): """ Returns a fraction that is the product of self and f PreC: f is either an int or a Fraction """ if isinstance(f,Fraction): # f is a Fraction N = self.num*f.num D = self.den*f.den else: # f is an int N = self.num*f D = self.den return Fraction(N,D) def negate(self): """ Returns the negative of self """ return Fraction(-self.num,self.den) def invert(self): """ Returns the reciprocal of self PreC: self is not zero """ return Fraction(self.den,self.num) def __eq__(self,f): """ Returns True if f and self represent the same fraction. False otherwise. """ return (self.num == f.num) and (self.den == f.den) if __name__ == '__main__': # Multiplication is commutative... F1 = Fraction(2,7) F2 = Fraction(3,11) if F1*F2 == F2*F1: print 'The Fraction F1*F2 equals the Fraction F2*F1' else: print 'Nope!' print '\n' # (p/q)*(q/p) = 1/1 F = F1*F1.invert() print F print '\n' # Computes 1 + 1/2 + 1/3 +...+ 1/n n = 30 s = Fraction(0) for k in range(1,n+1): s = s + Fraction(1,k) print s