Reducing Fraction to Lowest Term
Create a Python script that will reduce an input fraction to its lowest term.
4. Define a function that will accept two parameters (numerator, denominator) and will return the reduced fraction.
Sample Output 1:
Input a fraction: 4/6
Reduced fraction is 2/3
from math import gcd
def reduce_fraction(x, y): #4
d = gcd(x, y)
x = x // d
y = y // d
end = str(x) + "/" + str(y)
return end
error = 1
values = []
while error == 1:
you_fraction = input("Input a fraction: ")
values = you_fraction.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")
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])
result = reduce_fraction(a, b)
print("Reduce fraction is " + result)
Comments
Leave a comment