Answer to Question #332127 in Python for sandhya

Question #332127

proper fractions

Given two fractional values A/C ,B/D where A,B are numbers and C,D are denominators you 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

the 1st line of input contains two space separeted strings A/C, B/D

input:

1/2 1/4

o/p:

3/4

i/p:

1/2 3/4

o/p:

11/4(that means 1(1/4))

i/p:

1/3 2/3

o/p:

1


1
Expert's answer
2022-04-23T11:16:43-0400
def validate(data):
    values = data.split('/')
    if len(values) == 2 and all(i.isdigit() for i in values):
        if len(values) > 1 and int(values[1]) == 0:
            print("Invalid fraction")
            return True
        else:
            return False
    else:
        return True


def split(data):
    values = data.split('/')
    return values


def nsd(a, b):
    while a*b != 0:
        if a >= b:
            a = a % b
        else:
            b = b % a
    return a + b


def main():
    switch = '1'
    fractions = ['1', '2']
    you_fraction_split = []
    for i in range(2):
        while validate(fractions[i]) or switch == '1':
            data = input("Input a fractions: ")
            fractions = data.split(' ')
            switch = '0'
        you_fraction_split.append(split(fractions[i]))
    a = int(you_fraction_split[0][0])
    b = int(you_fraction_split[0][1])
    c = int(you_fraction_split[1][0])
    d = int(you_fraction_split[1][1])
    nsk = b * d // nsd(b, d)
    numerator = (int(a * (nsk/b))) + (int(c * (nsk/d)))
    denominator = nsk
    if numerator > denominator:
        print(str(numerator) + '/' + str(denominator) + '(that means ' + str(numerator//denominator) + '(' + str(numerator % denominator) + '/' + str(nsk) + '))')
    elif numerator == denominator:
        print(int(numerator/denominator))
    else:
        print(str(numerator) + '/' + str(denominator))


if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS