Create a Python script that will reduce an input fraction to its lowest term. The program requirements will be:
Sample Output:
Input a fraction? : 4/6
Reduced fraction is 2/3
I need the code to have an output stated above and that the requirements are met in the code.
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:
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