Answer to Question #332854 in Python for Dhea M. Maddela

Question #332854

Create a Python script that will reduce an input fraction to its lowest term. The program requirements will be:

  1. Function that will check first if the input fraction is a VALID fraction.
  2. Function that will split a VALID fraction and return a list that consists the numerator and denominator.
  3. Function that will accept two parameters (numerator and denominator) to determine the greatest common divisor.
  4. Function that will accept two parameters (numerator, denominator) and will return the reduced fraction.


Sample Output:

Input a fraction? : 4/6

Reduced fraction is 2/3


I need the code to have an output stated above and that the requirements are met in the code.


1
Expert's answer
2022-04-23T10:28:51-0400
 from math import gcd


def validate(data): #1
    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:
        print("It is not fraction")
        return True


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


def search_gcd(x, y): #3
    d = gcd(x, y)
    return d


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


def main():
    you_fraction = "a/b"
    while validate(you_fraction) or you_fraction == 'a/b':
        you_fraction = input("Input a fraction: ")

    you_fraction_split = split(you_fraction)
    a = int(you_fraction_split[0])
    b = int(you_fraction_split[1])
    my_gcd = search_gcd(a, b)
    print("Reduce fraction is " + reduce_fraction(a, b))


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