Reducing Fraction to Lowest Term
Create a Python script that will reduce an input fraction to its lowest term.
1. Define a function that will check first if the input fraction is a VALID fraction.
Sample Output 1:
Input a fraction: 4/6
Reduced fraction is 2/3
#Define a function will check fraction is a valid
def isValidFraction(s:str)->bool:
cntDef=0
for ch in s:
if ch=="/":
cntDef+=1
elif((not ch.isdigit())):
return False
return cntDef==1
#define function wich find GCD two numbers
def gcd(ad:int,bd:int)->int:
a=ad
b=bd
while a!=0 and b!=0:
if a>b:
a%=b
else:
b%=a
return a+b
s=input("Input a fraction: ")
if(isValidFraction(s)):
ls=list(map(int,s.split('/')))
gc=gcd(ls[0],ls[1])
ls[0]//=gc
ls[1]//=gc
#to reduce we need divide each term to gcd
print(str(ls[0])+"/"+str(ls[1]))
else:
print("Incorrect fraction")
Comments
Leave a comment