Reducing Fraction to Lowest Term
Create a Python script that will reduce an input fraction to its lowest term.
Program Requirements:
Function 1: Function that will check first if the input fraction is a VALID fraction:
Your answer:
Function 2: Function that will split a VALID fraction and return a list that consists the numerator and denominator.
Your answer:
Function 3: Function that will accept two parameters (numerator and denominator) to determine the greatest common divisor
Your answer:
Function 4: Function that will accept two parameters (numerator, denominator) and will return the reduced fraction:
Your answer:
Sample Output 1:
Input a fraction: 4/6
Reduced fraction is 2/3
def validFraction(f):
f = [_ for _ in f.split('/')]
if len(f) != 2:
return False
try:
if int(f[0]) == 0 or int(f[1]) == 0:
return False
except:
return False
return True
def splitFraction(f):
return [int(n) for n in f.split('/')]
def greatestCommonDivisor(n1, n2):
if n1 < 0:
n1 *= -1
if n2 < 0:
n2 *= -1
if n1 > n2:
n = n2
else:
n = n1
for i in range(n,0,-1):
if n2%i == 0 and n1%i == 0:
return i
return 1
def reduceFraction(n1, n2):
gcd = greatestCommonDivisor(n1, n2)
return [n1//gcd, n2//gcd]
fraction = input('Input a fraction: ')
if validFraction(fraction):
redFract = reduceFraction(*splitFraction(fraction))
redFract = str(redFract[0]) + '/' + str(redFract[1])
print('Reduced fraction is', redFract)
Comments
Leave a comment