In [64]:
class ZeroDivisionException(Exception):
pass
class Fraction():
def __init__(self, up, down):
if down == 0:
raise ZeroDivisionException
self.up = up
self.down = down
def __add__(self, other):
result = Fraction(self.up * other.down +self.down*other.up,
self.down*other.down).cancel()
return result
def __sub__(self, other):
result = Fraction(self.up * other.down -self.down*other.up,
self.down*other.down).cancel()
return result
def __mul__(self, other):
return Fraction(self.up * other.up, self.down * other.down).cancel()
def __truediv__(self, other):
return Fraction(self.up * other.down, self.down * other.up).cancel()
def __repr__(self):
return '{}/{}'.format(self.up, self.down)
def _gcd(self):
if self.up > self.down:
b = self.up
else:
b = self.down
for x in range(b, 0, -1):
if self.up % x == 0 and self.down % x == 0:
return x
return 1
def cancel(self):
gcd = self._gcd()
up = self.up // gcd
down = self.down // gcd
return Fraction(up, down)
In [66]:
print(Fraction(1,2) / Fraction(1,2))
print(Fraction(1,2) * Fraction(1,2))
print(Fraction(1,2) - Fraction(1,2))
print(Fraction(2,6) + Fraction(3,4))
In [60]:
Fraction(2,4).cancel()
Out[60]: