If you are using the fractions
library, ou can just sum everything, then take the int()
portion of the fraction:
def __add__(self, g):
summed = sum((self.whole_number, g.whole_number, self.fraction, g.fraction))
whole = int(summed)
remainder = summed - whole
return '{} and {}'.format(whole, remainder)
The Fraction()
class implements __add__
for you, you can just sum up integers and Fraction()
objects and it all works as it should.
Demo using constants:
>>> from fractions import Fraction
>>> summed = sum((2, 1, Fraction(3, 4), Fraction(2, 3)))
>>> whole = int(summed)
>>> remainder = summed - whole
>>> '{} and {}'.format(whole, remainder)
'4 and 5/12'
One little-known but handy factoid is that Python the int()
type has both .numerator
and .denominator
attributes, that the fractions.Fraction()
class makes use of. If you are not using the fractions
library, you can make use of that yourself:
def __add__(self, g):
summed = 0
for v in (self.whole_number, g.whole_number, self.fraction, g.fraction):
summed = Fraction(summed.numerator * v.denominator +
v.numerator * summed.denominator,
summed.denominator * v.denominator)
whole = summed._numerator // summed._denominator
remainder = Fraction(summed.numerator * whole.denominator -
whole.numerator * summed.denominator,
summed.denominator * whole.denominator)
return '{} and {}'.format(whole, remainder)