Answer to Question #332879 in Python for Katekeithruden

Question #332879

Reducing Fraction to Lowest Term


Create a Python script that will reduce an input fraction to its lowest term.


4. Define a function that will accept two parameters (numerator, denominator) and will return the reduced fraction.


Sample Output 1:


Input a fraction: 4/6


Reduced fraction is 2/3

1
Expert's answer
2022-04-26T09:28:09-0400
from math import gcd


def reduce_fraction(x, y): #4
    d = gcd(x, y)
    x = x // d
    y = y // d
    end = str(x) + "/" + str(y)
    return end


error = 1
values = []
while error == 1:
    you_fraction = input("Input a fraction: ")
    values = you_fraction.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")
            error = 1
        else:
            error = 0
    else:
        if you_fraction != 'a/b':
            print("It is not fraction")
        error = 1
a = int(values[0])
b = int(values[1])
result = reduce_fraction(a, b)
print("Reduce fraction is " + result)

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