3
votes

I am trying to add two fractions in python

if input 1/4 + 1/4, I am expecting 1/2 result

I built a fraction class with an __add__ method for addition

from fractions import gcd

class fraction:
    def __init__(self, numerator, denominator):
        self.num = numerator
        self.deno = denominator
    def __add__(self, other):
        self.sumOfn = self.num + other.num
        self.sumOfd = gcd(self.deno,other.deno)
        return(self.sumOfn, self.sumOfd)



print(fraction(1,4)+fraction(1,4))

However I am getting 2,4 as output, which is actually 1/2, just not simplified. How could I fix that problem ?

3
The general approach to simplifying fractions is to find the greatest common divisor of the numerator and denominator and then divide both of them by it. - Anthony Sottile
The fractions module already has a Fraction type. All you need is from fractions import Fraction and then print(Fraction(1,4)+Fraction(1,4)). - user2555451
@AnthonySottile it works I suggest you put the same answer below and I will select it as best answer - Mozein

3 Answers

4
votes

The general approach to simplifying fractions is to find the greatest common divisor of the numerator and denominator and then divide both of them by it

5
votes

As mentioned by @icodez

from fractions import Fraction
print(Fraction(1,4)+Fraction(1,4))
0
votes

This works :

class fraction:

def __init__(self, numerator, denominator):
    self.num = numerator
    self.deno = denominator

def __add__(self, other):
    self.sumOfn = self.num + other.num
    self.sumOfd = gcd(self.deno,other.deno)

    num=gcd(self.sumOfn,self.sumOfd)

    res_num=self.sumOfn/num
    res_den=self.sumOfd/num

    if res_num==res_den:print res_num
    else:print res_num,"/",res_den

(fraction(1,4)+fraction(1,4))