Question: using python 3: Write a magic method for the Fraction class to see if two fractions are equal in value (see the body of the
using python 3:
Write a magic method for the Fraction class to see if two fractions are equal in value (see the body of the sameRational function in activecode 2 on the previous page).
Below the class definition, try the magic method. For example, print(f1 == f2) and print(f2 ==f4)
def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n
class Fraction: def __init__(self, top, bottom): self.__num = top # the numerator is on top self.__den = bottom # the denominator is on the bottom
def __str__(self): return '{}/{}'.format(self.__num, self.__den)
def __add__(self,other): newnum = self.__num * other.__den + self.__den * other.__num newden = self.__den * other.__den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common)
f1 = Fraction(1, 6) f2 = Fraction(1, 2) f3 = f1 + f2 # + operation is the __add__ method print(f3) f4 = Fraction(5,10)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
