Created
January 1, 2016 03:43
-
-
Save sbstp/b4c975c55870e7f25686 to your computer and use it in GitHub Desktop.
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
class Rational(object): | |
def __init__(self, num, den): | |
self.num = num | |
self.den = den | |
def __add__(self, other): | |
if isinstance(other, int): | |
num = self.num + other * self.den | |
den = self.den | |
elif isinstance(other, Rational): | |
num = self.num * other.den + other.num * self.den | |
den = self.den * other.den | |
else: | |
raise TypeError | |
return Rational(num, den).simplify() | |
def __div__(self, other): | |
if isinstance(other, int): | |
num = self.num | |
den = self.den * other | |
elif isinstance(other, Rational): | |
num = self.num * other.den | |
den = self.den * other.num | |
else: | |
raise TypeError | |
return Rational(num, den).simplify() | |
def __mul__(self, other): | |
if isinstance(other, int): | |
num = self.num * other | |
den = self.den | |
elif isinstance(other, Rational): | |
num = self.num * other.num | |
den = self.den * other.den | |
else: | |
raise TypeError | |
return Rational(num, den).simplify() | |
def __str__(self): | |
if self.den == 1: | |
return str(self.num) | |
else: | |
return '{}/{}'.format(self.num, self.den) | |
def simplify(self): | |
if self.num % self.den == 0: | |
return Rational(self.num / self.den, 1) | |
else: | |
return self | |
if __name__ == '__main__': | |
a = Rational(1,2) | |
b = Rational(1,2) | |
print(a + 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment