Last active
January 4, 2016 19:09
-
-
Save pdparker/8665503 to your computer and use it in GitHub Desktop.
Class Fraction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on exercises from http://interactivepython.org/courselib/static/pythonds/Introduction/introduction.html