Answered step by step
Verified Expert Solution
Link Copied!

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 (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
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Transact SQL Cookbook Help For Database Programmers

Authors: Ales Spetic, Jonathan Gennick

1st Edition

1565927567, 978-1565927568

More Books

Students also viewed these Databases questions