Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Fractions Addition by Kurush
# (a, b) + (c, d) = (ad + bc, bd)
def add_fractions(fracts):
Sum = (0, 1)
for fract in fracts:
Sum = (Sum[0] * fract[1] + Sum[1] * fract[0], Sum[1] * fract[1])
Div = gcd(Sum[0], Sum[1])
Sum = (Sum[0] // Div, Sum[1] // Div)
Res = (Sum[0] // Sum[1], Sum[0] - (Sum[0] // Sum[1]) * Sum[1], Sum[1])
if (Res[0] != 0) and (Res[1] != 0): SRes = str(Res[0]) + ' and ' + str(Res[1]) + '/' + str(Res[2])
elif (Res[1] == 0): SRes = Res[0]
else: SRes = str(Res[1]) + '/' + str(Res[2])
return SRes
def gcd(a, b):
if a == b: return a
elif a > b: return gcd(a - b, b)
elif b > a: return gcd(b - a, a)
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!")
Feb. 4, 2019