Created
October 20, 2021 06:25
-
-
Save msyvr/f1039170f054821fee0833217a60dc46 to your computer and use it in GitHub Desktop.
mit 6.0001 - define Fraction class and methods
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 Fraction(object): | |
def __init__(self, num, den): | |
assert type(num) == int and type(den) == int and den != 0 | |
self.num = num | |
self.den = den | |
def __str__(self): | |
return self.num + "/" + self.den | |
def __add__(self, other): | |
num_add = self.num*other.den + self.den*other.num | |
den_add = self.den*other.den | |
return Fraction(num_add, den_add) | |
def __float__(self): | |
return self.num/self.den #dividing two ints yields a float | |
def inverse(self): | |
return Fraction(self.den, self.num) | |
a = Fraction(1, 4) | |
b = Fraction(3, 4) | |
c = a + b | |
print(float(c)) | |
print(Fraction.__float__(c)) | |
print(float(b.inverse())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment