Answer to Question #332878 in Python for Katekeithruden

Question #332878

Reducing Fraction to Lowest Term


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


3. Define a function that will accept two parameters (numerator and denominator to determine the greatest common divisor.


Sample Output 1:


Input a fraction: 4/6


Reduced fraction is 2/3

1
Expert's answer
2022-04-25T15:15:54-0400
"""This function that will accept two parameters numerator and denominator
to determine the greatest common divisor."""
def search_gcd(x, y):
    while x * y != 0:
        if x >= y:
            x = x % y
        else:
            y = y % x
    return x + y


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])
d = search_gcd(a, b)
a = a // d
b = b // d
result = str(a) + "/" + str(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