Answer to Question #332876 in Python for Katekeithruden

Question #332876

Reducing Fraction to Lowest Term


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


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


Sample Output 1:


Input a fraction: 4/6


Reduced fraction is 2/3

1
Expert's answer
2022-04-25T04:43:05-0400
from math import gcd

"""This is function that splits a REAL fraction and returns a list 'value' 
consisting of the numerator and denominator
"""
def split(data):
    values = data.split('/')
    return values


def main():
    error = 1
    values = []
    while error == 1:
        you_fraction = input("Input a fraction: ")
        values = split(you_fraction)
        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 = gcd(a, b)
    a = a // d
    b = b // d
    result = str(a) + "/" + str(b)
    print("Reduce fraction is " + result)


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