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 a ZeroDivisionError.
  • __str__: This method should return the fraction in the numerator / 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
f1 = Fraction(1, 2); f2 = Fraction(1, 3); f3 = f1+f2; print(f3)
5 / 6
f1 = Fraction(1, 2); f2 = Fraction(1, 3); f3 = f1-f2; print(f3)
1 / 6
f1 = Fraction(1, 2); f2 = Fraction(1, 3); f3 = f1 * f2; print(f3)
1 / 6
f1 = Fraction(1, 2); f2 = Fraction(1, 3); f3 = f1 / f2; print(f3)
3 / 2
f1 = Fraction(1, 2); f2 = Fraction(0, 3); f3 = f1 / f2; print(f3)
ZeroDivisionError: You can't divide by zero!
f1 = Fraction(1, 0);
ValueError: The denominator cannot be zero!
 

Constraints

Time limit: 2 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue