implemented reduce() and __nonzero__()
This commit is contained in:
44
frac.py
44
frac.py
@@ -8,10 +8,13 @@ import numbers
|
|||||||
|
|
||||||
class frac:
|
class frac:
|
||||||
|
|
||||||
def __init__(self, num, den):
|
def __init__(self, num, den, reduced = False):
|
||||||
|
if den == 0:
|
||||||
|
raise ValueError('frac denominator cannot be 0')
|
||||||
self.num = long(num)
|
self.num = long(num)
|
||||||
self.den = long(den)
|
self.den = long(den)
|
||||||
self.reduce()
|
if not reduced:
|
||||||
|
self.reduce()
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return 'frac(%d, %d)' % (self.num, self.den)
|
return 'frac(%d, %d)' % (self.num, self.den)
|
||||||
@@ -31,6 +34,12 @@ class frac:
|
|||||||
def __bool__(self):
|
def __bool__(self):
|
||||||
return bool(self.num)
|
return bool(self.num)
|
||||||
|
|
||||||
|
def __nonzero__(self):
|
||||||
|
return self.__bool__()
|
||||||
|
|
||||||
|
def __neg__(self):
|
||||||
|
return frac(-self.num, self.den, reduced=True)
|
||||||
|
|
||||||
def __add__(self, other):
|
def __add__(self, other):
|
||||||
if isinstance(other, frac):
|
if isinstance(other, frac):
|
||||||
newnum = self.num * other.den + other.num * self.den
|
newnum = self.num * other.den + other.num * self.den
|
||||||
@@ -133,4 +142,33 @@ class frac:
|
|||||||
return float(self) == other
|
return float(self) == other
|
||||||
|
|
||||||
def reduce(self):
|
def reduce(self):
|
||||||
pass
|
pos = True
|
||||||
|
if self.num < 0:
|
||||||
|
pos = not pos
|
||||||
|
self.num = -self.num
|
||||||
|
if self.den < 0:
|
||||||
|
pos = not pos
|
||||||
|
self.den = -self.den
|
||||||
|
com = frac.gcd(self.num, self.den)
|
||||||
|
self.num /= com if pos else -com
|
||||||
|
self.den /= com
|
||||||
|
|
||||||
|
#TODO: replace with more efficient version later
|
||||||
|
#https://en.wikipedia.org/wiki/Euclidean_algorithm
|
||||||
|
#if one number is 0 this returns the other number
|
||||||
|
#that works great for this application but may not for yours
|
||||||
|
@staticmethod
|
||||||
|
def gcd(num1, num2):
|
||||||
|
if num1 == 0:
|
||||||
|
return num2
|
||||||
|
elif num2 == 0:
|
||||||
|
return num1
|
||||||
|
elif num1 == num2:
|
||||||
|
return num1
|
||||||
|
elif num1 < num2:
|
||||||
|
temp = num1
|
||||||
|
num1 = num2
|
||||||
|
num2 = temp
|
||||||
|
return frac.gcd(num1 - num2, num2)
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user