$30
ECE-C301 Advanced Programming for Engineers
Homework Assignment: Week 2
Implement a class called Fraction that defines an immutable rational number. Users of your class should
be able to work with fractions using the traditional operators—specifically your class should implement the
following “magic methods”:
• init – Construct a rational number with a given numerator and denominator
• add – Add two Fraction instances
• sub – Subtract two Fraction instances
• eq – Check if two Fraction instances are equal
• lt – Check if one Fraction instance is less than the other
• ne – Check if two Fraction instances are not equal
• le – Check if one Fraction instance is less than or equal to the other
• gt – Check if one Fraction instance is greater than the other
• ge – Check if one Fraction instance is greater than or equal to the other
• float – Gets a floating point representation of a Fraction instance, called by float()
• repr – Gets a string representation of the Fraction instance, called by str()
– Save your Fraction class implementation in a file called fraction.py.
Write a small test program that imports fraction.py as follows:
1 from fraction import Fraction
and use your Fraction class to clearly demonstrate that all of your magic methods work properly.
– Save your test program in a file called test.py
– Save the output of your test program in a file called output.txt
1
Submitting Your Assignment
Create a zip file containing the following files:
• fraction.py – contains your Fraction class implementation
• test.py – contains your test program for the Fraction class
• output.txt – contains the output of test.py
name your zip file using your Drexel user id. For example: HW2 abc123.zip. Upload your zip file to
learn.drexel.edu using the assignment submission link.
2