Lab 6

Programming exercises.

  1. Add Triangle and Point class to the shape package in lab2, use Point to rewrite all classes and add an area() method to both Triangle and Circle so that area of object will be displayed when drawn.

    Include doc string comment in all your modules. After testing, use pydoc to generate class documentation in HTML format.

  2. A rational number is any number that can be expressed as the quotient or fraction n/d of two integers.

    Define a Python class called Rational. Every Rational object consists of two attributes n and d representing the numerator and denominator.

    • Note that n and d should both be integers. Ensure this by having the instantiation method throw an appropriate exception otherwise.
    • Further, d could not be zero and should always be positive. Extend the instantiation method so that if d is zero an exception is thrown; while if d is negative the equivalent object is created with attributes -n,-d.
    • Write a __str__ method that converts a Rational instance to the string "n/d".
    • Use names in Python arithmetic methods to implement the appropriate arithmetic special methods for the class Rational.

      Recall the following rules for arithmetic with fractions.

    • Note that different Rational objects can be mathematically equal. For example, 2/4 = 1/2. In general n1/d1 = n2/d2 if and only if n1*d2 = n2*d1. Write a method that takes two Fraction objects; and returns True is they are mathematically equal and False otherwise. Give it the appropriate special method name so that Python will use it when checking equality of two Rational objects with ==.
    • You could write similar methods for checking whether one fraction is bigger or smaller than another.
    • All equivalent mathematical fractions can be simplified to a unique form by cancelling common factors in the numerator and detonator. Write a function to reduce the rational to its lowest form. Make this a method of the class and run it as part of the instantiation of any Rational object.