# simplefrac.py # Walker M. White (wmw2) # October 15, 2015 """Module with a simple Fraction class. This module implements a fraction WITHOUT using operator overloading. It is an example of the simplest way to use a class.""" def gcd(a,b): """Returns: Greatest common divisor of x and y. Precondition: x and y are integers.""" assert type(a) == int,`x`+' is not an int' assert type(b) == int,`y`+' is not an int' while b != 0: t = b b = a % b a = t return a class Fraction(object): """Instance is a fraction n/d INSTANCE ATTRIBUTES: numerator: The fraction numerator [int] denominator: The fraction denomenator [int > 0] """ # INITIALIZER def __init__(self,n=0,d=1): """Initializer: Creates a new Fraction n/d Parameter n: the numerator (default is 0) Precondition: n is an int (or optional) Parameter d: the denomenator (default is 1) Precondition: d is an int (or optional) """ assert type(n) == int,`n`+' is not an int' assert type(d) == int,`d`+' is not an int' assert d > 0,`d`+' is not positive' self.numerator = n self.denominator = d def mult(self,other): """Returns: Product of self and other as a new Fraction This method does not modify the contents of self or other Parameter other: the fraction to multiply on the right Precondition: other is a Fraction""" assert type(other) == Fraction top = self.numerator*other.numerator bot = self.denominator*other.denominator return Fraction(top,bot) def add(self,other): """Returns: Sum of self and other as a new Fraction This method does not modify the contents of self or other Parameter other: the fraction to add on the right Precondition: other is a Fraction""" assert type(other) == Fraction bot = self.denominator*other.denominator top = (self.numerator*other.denominator+ self.denominator*other.numerator) result = Fraction(top,bot) return result def reduce(self): """Normalizes this fraction into simplest form. Normalization ensures that the numerator and denominator have no common divisors.""" g = gcd(self.numerator,self.denominator) self.numerator = self.numerator/g self.denominator = self.denominator/g