Question: Write a Fraction class ( fraction.py ) that represents a rational number ( i . e . , numbers that can be expressed in the

Write a Fraction class (
fraction.py) that represents a rational number (i.e., numbers that can be
expressed in the form of ab, where a and b are integers). For example, a variable with a value
of 12 would be created as follow:
one_half =Fraction(1,2)
Your class should provide access to the numerator and denominator through the methods
numerator and denominator, and support the following methods/operations:
repr__(self): return a string representation of a Fraction object, e.g., Fraction(1,2).
(self): return a string value of a Fraction object, e.g.,1/2.
Add, subtract, multiply, and divide fractions. Each method should return a Fraction object with
the answer and be implemented by overloading the appropriate operator.
Comparisons: ==,!=,=,>=,,>
Your Fraction class should ensure that your fractions are represented using a canonical (unique)
form. That is, your fractions should be in reduced form. Other questions to consider are 1) how
0 is represented and 2) how a negative number is represented. Handling these questions about
fraction representation are part of robust programming.
Greatest common divisor: To represent a fraction in reduced form, you need to calculate the
greatest common divisor of the numerator and denominator. This can be done using the
Euclidean algorithm. Assume that we want gcd(a,b), where ab>0. Then, using integer
arithmetic, we can calculate the gcd using the following algorithm:
r=amodb
while r is not zero:
a=b
b=r
r=amodb
return b
The value b returned by this method is gcd(a,b). For full marks, you need to write your own
version of the gcd() function. The ) function is available in the math module, but we want
you to write your own as an exercise. As an added challenge, see if you can write ) as a
recursive function; there are no extra marks for a recursive version.
Finally, write a simple program to test your Fraction class. Add your test code at the end of the
file. The text below demonstrates output from sample test code; use it as a guide.
using python
 Write a Fraction class ( fraction.py) that represents a rational number

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!