Skip to content

Instantly share code, notes, and snippets.

@aldraco
Created September 28, 2015 16:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aldraco/15236a4dfaf76e866fc0 to your computer and use it in GitHub Desktop.
Save aldraco/15236a4dfaf76e866fc0 to your computer and use it in GitHub Desktop.
Learning Python - class for Rational numbers, inspired by interactivepython.org's exercises.
def gcd(m,n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
class Rational:
def __init__(self, n, d):
factor = gcd(n, d)
self.numer = n // factor
self.denom = d // factor
def __str__(self):
# must return a string
if (self.denom == 1):
return str(self.numer)
else:
return str(self.numer) + "/" + str(self.denom)
def __add__(self, other):
return Rational(self.numer + other.numer, self.denom + other.denom)
def __sub__(self, other):
fac1 = other.denom
fac2 = self.denom
return Rational(self.numer * fac1 - other.numer * fac2, self.denom * other.denom)
def __mul__(self, other):
return Rational(self.numer * other.numer, self.denom * other.denom)
def __floordiv__(self, other):
return self * other.inverse()
def __eq__(self, other):
# put both fractions in same terms
fac1 = other.denom
fac2 = self.denom
self.numer = self.numer * fac1
self.denom = self.denom * fac1
other.numer = other.numer * fac2
other.denom = other.denom * fac2
return self.numer == other.numer
def inverse(self):
return Rational(self.denom, self.numer)
@jaatine2
Copy link

I think addition should be:
return Rational((self.numerother.denom)+(other.numerself.denom), (self.denom*other.denom))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment