Answer to Question #333003 in Python for Kian

Question #333003

Kaye Keith C. Ruden


Machine Problem 3


Reducing Fraction to Lowest Term


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


Program Requirements:


1. Define a function that will check first if the input fraction is a VALID fraction.


2. Define a function that will split a VALID fraction and return a list that consists the numerator and denominator.


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


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


Sample Output:


Input a fraction?: 5/0


Invalid fraction

1
Expert's answer
2022-04-26T09:28:06-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:
        if you_fraction != 'a/b':
            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