Skip to content

Instantly share code, notes, and snippets.

@pdparker
Last active January 4, 2016 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdparker/8665503 to your computer and use it in GitHub Desktop.
Save pdparker/8665503 to your computer and use it in GitHub Desktop.
Class Fraction
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num)+"/"+str(self.den)
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 __sub__(self,otherfraction):
newnum = self.num*otherfraction.den + \
-(self.den*otherfraction.num)
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
if newnum == 0:
return 0
else:
return Fraction(newnum//common,newden//common)
def __mul__(self,otherfraction):
newnum = self.num*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __div__(self,otherfraction):
newnum = self.num*otherfraction.den
newden = self.den * otherfraction.num
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
def __lt__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum < secondnum
def __gt__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum > secondnum
def __le__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum <= secondnum
def __ge__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum >= secondnum
def __ne__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum < secondnum
@pdparker
Copy link
Author

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