Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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 ie numbers that can be
expressed in the form of where a and are integers For example, a variable with a value
of would be created as follow:
onehalf Fraction
Your class should provide access to the numerator and denominator through the methods
numerator and denominator, and support the following methodsoperations:
reprself: return a string representation of a Fraction object, eg Fraction
self: return a string value of a Fraction object, eg
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 how
is represented and 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 where Then, using integer
arithmetic, we can calculate the gcd using the following algorithm:
amodb
while is not zero:
amodb
return b
The value returned by this method is For full marks, you need to write your own
version of the 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
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started