Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Write a Frac tion class ( frac tion.py ) that represents a ra tional number ( i . e . , numbers that can be

Write a Frac
tion class (frac
tion.py) that represents a ra
tional number (i.e., numbers that can be
expressed in the form of a/b, where a and b are integers). For example, a variable with a value
of (1)/(2) would be created as follow:
one_half = Frac
tion(1,2)
Your class should provide access to the numerator and denominator through the methods
numerator and denominator, and support the following methods/opera
tions:
__repr__(self): return a string representa
tion of a Frac
tion object, e.g., Frac
tion(1,2).
__str__(self): return a string value of a Frac
tion object, e.g.,1/2.
Add, subtract, mul
tiply, and divide frac
tions. Each method should return a Frac
tion object with
the answer and be implemented by overloading the appropriate operator.
Comparisons: ==,!=,<=,>=,<,>
Your Frac
tion class should ensure that your frac
tions are represented using a canonical (unique)
form. That is, your frac
tions should be in reduced form. Other ques
tions to consider are 1) how
0 is represented and 2) how a nega
tive number is represented. Handling these ques
tions about
frac
tion representa
tion are part of robust programming.
Greatest common divisor: To represent a frac
tion 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 a >= b >0. Then, using integer
arithme
tic, we can calculate the gcd using the following algorithm:

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

Students also viewed these Databases questions