RationalNumber Class
Your task is to define a
RationalNumber
class in Python. This class should be used to represent a rational number, a number that can be expressed as the quotient of two integers (numerator and denominator).The
RationalNumber
class should have the following characteristics:- The class should have two private integer attributes, the
numerator
and thedenominator
of the rational number.
- The class should define the magic methods
__add__
,__sub__
,__mul__
, and__truediv__
to add, subtract, multiply, and divide two rational numbers, respectively.
- Addition, subtraction, multiplication, and division operations should be performed in a way that's mathematically accurate for rational numbers, with the result being another instance of
RationalNumber
.
- The class should reduce the rational number to its simplest form by dividing the numerator and denominator by their greatest common divisor (GCD).
- The class should implement the
__str__
magic method that should return a string<numerator> / <denominator>
in its simplest form.
Input | Output |
print(RationalNumber(1, 2) + RationalNumber(1, 3)); print(RationalNumber(1, 2) - RationalNumber(1, 3)); print(RationalNumber(1, 2) * RationalNumber(1, 3)); print(RationalNumber(1, 2) / RationalNumber(1, 3)); | 5 / 6
1 / 6
1 / 6
3 / 2 |
Constraints
Time limit: 1 seconds
Memory limit: 512 MB
Output limit: 1 MB