Skip to content
Advertisement

GCD implementation of fraction addition not working properly

I am following the Runestone Academy Python3 course and tried to implement ‘addition’ feature for fractions using Class but I am getting error.

When I am not using GCD implementation, the code is running fine

Here is my code:

class Fraction:

    def __init__(self, top, bottom):
        self.num = top
        self.den = bottom

    def show(self):
        print(f'{self.num}/{self.den}')

    def __str__(self):
        return f'{self.num}/{self.den}'

    # adding without GCD implementation

    # def __add__(self,other_fraction):
    #     new_num = self.num * other_fraction.den + self.den * other_fraction.num
    #     new_den = self.den * other_fraction.den

    #     return Fraction(new_num, new_den)

    # adding with GCD implementation

    def gcd(self, m, n):
        while m % n != 0:
            m, n = n, m % n

        return n

    def __add__(self, other_fraction):
        new_num = self.num * other_fraction.den + self.den * other_fraction.num
        new_den = self.den * other_fraction.den
        common = gcd(new_num, new_den)

        return Fraction(new_num // common, new_den // common)

    # my attempt of adding two fractions by creating a method 'add'

    # def add(self,other_fraction):
    #     new_num = self.num * other_fraction.den + self.den * other_fraction.num
    #     new_den = self.den * other_fraction.den

    #     return Fraction(new_num, new_den)


# my_fraction = Fraction(3,5)
# print(my_fraction)
# print(f'I ate {my_fraction} of my pizza')
# my_fraction.__str__()
# str(my_fraction)

f1 = Fraction(1, 4)
f2 = Fraction(1, 2)
f3 = f1 + f2
# f3 = f1.add(f2)
print(f3)

This is the error I am getting:

Traceback (most recent call last):
  File "D:/Python/Mosh_Lec/app.py", line 74, in <module>
    f3 = f1 + f2
  File "D:/Python/Mosh_Lec/app.py", line 53, in __add__
    common = gcd(new_num, new_den)
NameError: name 'gcd' is not defined

I also tried with this variation but same error:

    def gcd(self, m, n):
        self.num = m
        self.den = n
        while self.num % self.den != 0:
            self.num, self.den = self.den, self.num % self.den

        return self.den

Advertisement

Answer

The gcd method should not logically be part of the Fraction class. Indeed, you can call the gcd method with any two numbers, they do not need to be the numerator and denominator of a fraction. Therefore I would move the gcd function outside of the class.

def gcd(m, n):
    ...

class Fraction:
    ...
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement