Skip to content

Instantly share code, notes, and snippets.

@LouiS0616
Created October 23, 2018 11:30
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 LouiS0616/9688628d2fe7bff839cec4d584a07e32 to your computer and use it in GitHub Desktop.
Save LouiS0616/9688628d2fe7bff839cec4d584a07e32 to your computer and use it in GitHub Desktop.
import math
def compute_lcm(a, b):
return (a * b) // math.gcd(a, b)
class MyFraction:
def __init__(self, numerator, denominator=1):
if denominator == 0:
raise ValueError
if denominator < 0:
numerator *= -1
denominator *= -1
gcd = math.gcd(numerator, denominator)
self._numerator = numerator // gcd
self._denominator = denominator // gcd
@property
def numerator(self):
return self._numerator
@property
def denominator(self):
return self._denominator
@property
def reciprocal(self):
if self.denominator == 0:
raise ValueError
return MyFraction(
self.denominator, self.numerator
)
def is_integer(self):
return self.denominator == 1
def __str__(self):
if self.is_integer():
return f'{self.numerator}'
return f'{self.numerator}/{self.denominator}'
def __eq__(self, other):
if isinstance(other, int):
return self == MyFraction(other)
if isinstance(other, MyFraction):
return (self.numerator == other.numerator) \
and (self.denominator == other.denominator)
return False
def __add__(self, other):
if isinstance(other, int):
return self + MyFraction(other)
if isinstance(other, MyFraction):
denominator, numerators = MyFraction.reduce(self, other)
return MyFraction(
sum(numerators), denominator
)
raise TypeError
def __radd__(self, other):
return self + other
def __sub__(self, other):
if isinstance(other, (int, MyFraction)):
return self + (-1 * other)
raise TypeError
def __rsub__(self, other):
return other + (-1 * self)
def __mul__(self, other):
if isinstance(other, int):
return self * MyFraction(other)
if isinstance(other, MyFraction):
return MyFraction(
self.numerator * other.numerator,
self.denominator * other.denominator
)
raise TypeError
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
if other == 0:
raise ValueError
if isinstance(other, int):
return MyFraction(
self.numerator, self.denominator * other
)
if isinstance(other, MyFraction):
return self * other.reciprocal
raise TypeError
def __rtruediv__(self, other):
return other * self.reciprocal
@staticmethod
def reduce(*fracs):
lcm = compute_lcm(
*(frac.denominator for frac in fracs)
)
return lcm, [
frac.numerator * (lcm // frac.denominator) for frac in fracs
]
frac1 = MyFraction(1, 7)
frac2 = MyFraction(-7, 5)
print(frac1 / frac2)
print(2 / frac2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment