Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

[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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Fundamentals Of Database Systems

Authors: Ramez Elmasri, Shamkant B. Navathe

7th Edition Global Edition

ISBN: 1292097612, 978-1292097619

More Books

Students also viewed these Databases questions