Answer to Question #333396 in Python for Mikaa

Question #333396

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: 4/6


Reduced fraction is 2/3

1
Expert's answer
2022-04-25T04:43:09-0400
def valid (fract):
    try:
        n, d = fract.split('/')
        n = int(n)
        d = int(d)
        if n == 0 or d == 0:
            raise
    except:
        return False
    return True


def split_frac (fract):
    n, d = fract.split('/')
    n = int(n)
    d = int(d)
    return n, d


def gcd (n, d):
    if n < 0:
        n *= -1
    if d < 0:
        d *= -1
    if n < d:
        n, d = d, n
    while d != 0:
        r = n % d
        n, d = d, r
    return n


def reduce_frac (n ,d):


    if d < 0:
        n *= -1
        d *= -1
    cmd = gcd( n, d )
    n = n // cmd
    d = d // cmd
    return f'{n}/{d}'


frac = input('Input a fraction: ')
if valid (frac):
    print(f'Reduced fraction is {reduce_frac (*split_frac (frac))}')
else:
    print('invalid input')

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