Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
sub f-string solution in Clear category for Fractions Addition by CDG.Axel
from fractions import Fraction
def add_fractions(fracts):
f = sum(Fraction(*i) for i in fracts) # starmap is longer
d, m = divmod(*f.as_integer_ratio())
return f'{f"{d} and " if d else ""}{f-d}' if m else d
if __name__ == '__main__':
print("Example:")
print(add_fractions(((2, 3), (2, 3))))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert add_fractions(((2, 3), (2, 3))) == "1 and 1/3"
assert add_fractions(((1, 3), (1, 3))) == "2/3"
assert add_fractions(((1, 3), (1, 3), (1, 3))) == 1
print("Coding complete? Click 'Check' to earn cool rewards!")
Nov. 14, 2021