Fraction Class
You are developing a simple calculator and your task is to create a Python class Fraction
which represents a mathematical fraction.
The class should have 5 magic methods:
__add__
: This method should take another Fraction object as an argument and return a new Fraction object which is the sum of the original Fraction and the argument Fraction.__sub__
: This method should take another Fraction object as an argument and return a new Fraction object which is the result of the original Fraction subtracted by the argument Fraction.__mul__
: This method should take another Fraction object as an argument and return a new Fraction object which is the result of the original Fraction multiplied by the argument Fraction.__truediv__
: This method should take another Fraction object as an argument and return a new Fraction object which is the result of the original Fraction divided by the argument Fraction. If the argument Fraction has a numerator of zero, this method should raise aZeroDivisionError
.__str__
: This method should return the fraction in thenumerator / denominator
format. The method should return a string representation of the fraction in its simplest form (for example, "2 / 3" instead of "4 / 6"). To simplify a fraction, divide the numerator and the denominator by their greatest common divisor (GCD).
The Fraction class should be able to be instantiated with two parameters, a numerator
and a denominator
. Both parameters should be integers, with the denominator
defaulting to 1
if not provided. If the denominator is 0, the program should raise a ValueError
in the __init__
method.
Input | Output |
---|---|
| 5 / 6 |
| 1 / 6 |
| 1 / 6 |
| 3 / 2 |
| ZeroDivisionError: You can't divide by zero! |
| ValueError: The denominator cannot be zero! |
Constraints
Time limit: 2 seconds
Memory limit: 512 MB
Output limit: 1 MB