Skip to content

Instantly share code, notes, and snippets.

@sodastsai
Created October 19, 2012 10:20
Show Gist options
  • Save sodastsai/3917350 to your computer and use it in GitHub Desktop.
Save sodastsai/3917350 to your computer and use it in GitHub Desktop.
Fraction
'''
Created on Feb 11, 2012
@author: sodas
'''
class Fraction (object):
def __init__(self, numerator, denominator):
self.numerator = numerator
if denominator == 0:
raise ValueError, 'Denominoator should not be %s'%denominator
self.denominator = denominator
def refactor(self):
def gcd(a,b):
if b==0: return a
else: return gcd(b, a%b)
factor = gcd(self.numerator, self.denominator)
self.numerator /= factor
self.denominator /= factor
def floatValue(self):
return float(self.numerator)/float(self.denominator)
def __str__(self):
return '%d/%d'%(self.numerator, self.denominator)
def __add__(self, other):
n1 = self.numerator
d1 = self.denominator
n2 = other.numerator
d2 = other.denominator
resultN = n1*d2 + n2*d1
resultD = d1*d2
result = Fraction(resultN, resultD)
result.refactor()
return result
def __sub__(self, other):
n1 = self.numerator
d1 = self.denominator
n2 = other.numerator
d2 = other.denominator
resultN = n1*d2 - n2*d1
resultD = d1*d2
result = Fraction(resultN, resultD)
result.refactor()
return result
def __mul__(self, other):
n1 = self.numerator
d1 = self.denominator
n2 = other.numerator
d2 = other.denominator
resultN = n1*n2
resultD = d1*d2
result = Fraction(resultN, resultD)
result.refactor()
return result
def __div__(self, other):
n1 = self.numerator
d1 = self.denominator
n2 = other.numerator
d2 = other.denominator
resultN = n1*d2
resultD = d1*n2
result = Fraction(resultN, resultD)
result.refactor()
return result
def __eq__(self, other):
return self.numerator*other.denominator == self.denominator*other.numerator
def __lt__(self, other):
return self.numerator*other.denominator < self.denominator*other.numerator
def __gt__(self, other):
return self.numerator*other.denominator > self.denominator*other.numerator
def __le__(self, other):
return self.numerator*other.denominator <= self.denominator*other.numerator
def __ge__(self, other):
return self.numerator*other.denominator >= self.denominator*other.numerator
if __name__=='__main__':
f1 = Fraction(1,3)
f2 = Fraction(1,4)
f3 = Fraction(1,2)
try:
f4 = Fraction(1,0)
except ValueError,e:
print e
print f1+f2
print f1<f2
print f1>=f2
print f3+f2
print f1*f2
print f1.floatValue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment