'__truediv__ method in a Fraction class
I have written a Fraction class and the __truediv__ method to divide two fractions. But I don't know what to put into the __truediv__ so that it prints out the division of two mentioned fractions.
class Fraction:
def __init__(self, numerator = 0, denominator = 1):
self.numerator = numerator
self.denominator = denominator
def __truediv__(self, other):
return Fraction(other.denominator//self.numerator,
self.denominator * other.numerator)
>>>fraction1 = Fraction(1, 2)
fraction2 = Fraction(3, 4)
fraction3 = fraction1 / fraction2
print(fraction3)
Solution 1:[1]
I think your math is a bit rusty, instead of:
return Fraction(other.denominator//self.numerator, self.denominator * other.numerator)
You should have:
return Fraction(other.denominator * self.numerator, self.denominator * other.numerator)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bes Dollma |
