Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
class Fraction: def __init__(self, num, den): from math import gcd g = gcd(abs(num), abs(den)) self.num = num // g self.den = den // g def __repr__(self): return f"Fraction({self.num}, {self.den})" def __str__(self): return f"{self.num}/{self.den}" def __add__(self, other): return Fraction(self.num * other.den + other.num * self.den, self.den * other.den) def __eq__(self, other): return self.num == other.num and self.den == other.den a = Fraction(1, 2) b = Fraction(1, 3) print(a + b) # 5/6 print(repr(a)) # Fraction(1, 2) print(a == Fraction(2, 4)) # True
Result
Open