Skip to content

Instantly share code, notes, and snippets.

@msyvr
Created October 20, 2021 06:25
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 msyvr/f1039170f054821fee0833217a60dc46 to your computer and use it in GitHub Desktop.
Save msyvr/f1039170f054821fee0833217a60dc46 to your computer and use it in GitHub Desktop.
mit 6.0001 - define Fraction class and methods
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