Question: [PYTHON]: Write three special methods for the Fraction class that overload operators to perform rich comparisons between a and b. (a < b, a >

[PYTHON]: Write three special methods for the Fraction class that overload operators to perform rich comparisons between a and b. (a < b, a > b, a==b).

class Fraction: def __init__(self, numerator, denominator): if denominator==0: raise ZeroDivisionError("Denominator cannot be zero") return self.n = numerator self.d = denominator

def __add__(self, other): n = self.n * other.d + self.d * other.n d = self.d * other.d return Fraction(n, d)

def __sub__(self, other): n = self.n * other.d - self.d * other.n d = self.d * other.d return Fraction(n, d)

def __mul__(self, other): n = self.n * other.n d = self.d * other.d return Fraction(n, d)

def __truediv__(self, other): n = self.n * other.d d = self.d * other.n return Fraction(n, d)

def __str__(self): return "{}/{}".format(self.n, self.d)

__repr__ = __str__

#Im not sure what to do as I was just given this set of code along with the problem. The outputs should match below:

>>> a = Fraction(1, 2)

>>> b = Fraction(1, 3)

>>> a== b

False # Boolean value, not a string

>>> a > b

True # Boolean value, not a string

>>> a < b

False # Boolean value, not a string

>>> a = Fraction(4, 8)

>>> b = Fraction(2, 4)

>>> a== b

True # Boolean value, not a string

>>> a > b

False # Boolean value, not a string

>>> a < b

False # Boolean value, not a string

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!