Proper Fractions
Given 2 fractional values A/C. B/D where A, B are numerators and C. D are denominators. You are asked to add two fractional values. If the sum gives proper fraction as output print the proper fraction. If it is improper, convert it into a mixed fraction and print it. If it is a whole number, print it.
Input
The first line of input contains two space-separated strings A/C &B/D
Output
The output should be a string of format p/q if the result is a proper fraction
a b/c if the result is a improper or med fraction
a if the result is a whole number
import sys
from fractions import Fraction
_, *args = sys.argv
a, c, b, d = [int(str) for arg in args for str in arg.split('/')]
sum = Fraction(a, c) + Fraction(b, d)
if sum.denominator == 1:
print(sum.numerator)
elif sum.numerator > sum.denominator:
whole_part = int(sum.numerator / sum.denominator)
print(f'{whole_part} {sum.numerator % sum.denominator}/{sum.denominator}')
else:
print(f'{sum.numerator % sum.denominator}/{sum.denominator}')
Comments
Leave a comment