0

Trying to call the gcd from the constructor but I keep getting either a global error or gcd is not defined error. Any suggestions? The program is supposed to reduce fractions immediately. So I got rid of the add.

class Fraction:
    def __init__(self,m,n):
        self.num = m
        self.den = n
        gcd()
        

    def __str__(self):
        return str(self.num)+"/"+str(self.den)

    def show(self):
        print self.num,"/",self.den

    #Assume that m and n are greater than zero
    def gcd(m,n):
        while m%n != 0:
            oldm = m
            oldn = n

            m = oldn
            n = oldm%oldn
        return n

    """def __add__(self,otherfraction):
        newnum = self.num*otherfraction.den + \
                     self.den*otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum,newden)
        return Fraction(newnum/common,newden/common)"""

    def __cmp__(self,otherfraction):
        num1 = self.num*otherfraction.den
        num2 = self.den*otherfraction.num
        if num1 < num2:
    	     return -1
    	else:
            if num1 == num2:
                return 0
            else:
                return 1

Edited by Ghostenshell: Added what the program should be doing.

2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by -ordi-
1
class Fraction:
  def __init__(self):
    pass
  def gcd(self, n, m):
    while m % n != 0:
      m, n = n, m %  n
    return n
    
n = Fraction()
print n.gcd(6, 3)

from fractions import gcd

print gcd(6, 3)

Edited by -ordi-: n/a

Votes + Comments
nice
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.