Equivalent support for built-in faction class

class Fraction:
    """Class for performing fraction arithmetic.
    Each Fraction has two attributes: a numerator, n and a deconominator, d.
    Both must be integer and the deonominator cannot be zero."""

    def __init__(self,n,d):
        """Performs error checking and standardises to ensure denominator is 
positive"""
        if type(n)!=int or type(d)!=int:
            raise TypeError("n and d must be integers")
        if d==0:
            raise ValueError("d must be positive")
        elif d<0:
            self.n = -n
            self.d = -d
        else:
            self.n = n
            self.d = d

    def __str__(self):
        """Gives string representation of Fraction (so we can use print)"""
        return(str(self.n) + "/" + str(self.d))

    def __add__(self, otherFrac):
        """Produces new Fraction for the sum of two Fractions"""
        newN = self.n*otherFrac.d + self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __sub__(self, otherFrac):
        """Produces new Fraction for the difference between two Fractions"""        
        newN = self.n*otherFrac.d - self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __mul__(self, otherFrac):
        """Produces new Fraction for the product of two Fractions"""        
        newN = self.n*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __truediv__(self, otherFrac):
        """Produces new Fraction for the quotient of two Fractions"""        
        newN = self.n*otherFrac.d
        newD = self.d*otherFrac.n
        newFrac = Fraction(newN, newD)
        return(newFrac)

      

As shown above how can I print

Fraction(1,3) == Fraction(2,6)

      

As an example:

Fraction(1,2) + Fraction(1,3)
Fraction(1,2) - Fraction(1,3)
Fraction(1,2) * Fraction(1,3)
Fraction(1,2) / Fraction(1,3)

      

They all work to calculate every time. And when I try to print fraction (1,3) == fraction (2.6) it comes out like False

. How can I calculate it like True

?

How to do it without using import fraction

.

+3


source to share


3 answers


Try the following:

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

      

As pointed out in the comments, there is no need to implement __ne__

.

EDIT: As requested in the comments to this answer, here's a method to simplify fractions.



Fraction simplification involves dividing both numbers by the greatest common factor. As stated in here , the code is pretty simple

# return the simplified version of a fraction
def simplified(self):
    # calculate the greatest common divisor
    a = self.n
    b = self.d
    while b:
        a, b = b, a%b
    # a is the gcd
    return Fraction(self.n/a, self.d/a)

      

Hope this helps.

+3


source


A model is defined __eq__

as a method that implements validation ==

.

A very simple implementation __eq__

would be:

def __eq__(self, other):
    return self.n == other.n and self.d == other.d

      



This will work for Fraction(1, 2) == Fraction(1, 2)

, but it won't work for Fraction(1, 2) == Fraction(2, 4)

.

You will need to change the contents of the method __eq__

to even allow for multiplicity comparisons.

+2


source


In python, to get custom behavior for the == operator, you must provide a method implementation __eq__

. If you don't override it, the default behavior is to check if the objects are indeed the same object, which in this case they are not.

+1


source







All Articles