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
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 data != '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()
Comments
Leave a comment