'''A simple class for representing fractions. Jeff Ondich, 10 Dec 2006 Each object of class Fraction represents a single fraction. This class is intended as an illustration of a few simple properties of Python classes--not as a complete implementation of the notion of a fraction. ''' class Fraction: def __init__(self, num, denom): self.numerator = num self.denominator = denom def __str__(self): return '%d/%d' % (self.numerator, self.denominator) def __add__(self, other): ''' Returns a new Fraction object containing the sum of this Fraction and the Fraction object other. ''' num = self.numerator * other.denominator + other.numerator * self.denominator denom = self.denominator * other.denominator newFraction = Fraction(num, denom) newFraction.reduce() return newFraction def add(self, other): ''' Adds the Fraction object "other" to the Fraction object self. ''' self.numerator = self.numerator * other.denominator + other.numerator * self.denominator self.denominator = self.denominator * other.denominator self.reduce() def subtract(self, other): ''' Subtracts the Fraction object "other" from the Fraction object self. ''' self.numerator = self.numerator * other.denominator - other.numerator * self.denominator self.denominator = self.denominator * other.denominator self.reduce() def multiply(self, other): ''' Multiplies this Fraction object by the Fraction object "other". ''' self.numerator = self.numerator * other.numerator self.denominator = self.denominator * other.denominator self.reduce() def reduce(self): ''' Reduces this Fraction. After calling reduce() on a Fraction object, the fraction will be in lowest terms (that is, its numerator and denominator will be relatively prime). ''' factor = min(self.numerator, self.denominator) while factor >= 1: if self.numerator % factor == 0 and self.denominator % factor == 0: self.numerator = self.numerator / factor self.denominator = self.denominator / factor return factor = factor - 1 if __name__ == '__main__': f = Fraction(117, 18) print 'Here is a fraction:', f f.reduce() print 'Here is the same fraction in lowest terms:', f print a = Fraction(5, 6) b = Fraction(4, 5) sum = a + b print 'Adding fractions:', a, '+', b, '=', sum print 'Multiplying fractions:', a, '*', b, '=', a.multiply(b) print a