Answer to Question #332875 in Python for Katekeithruden

Question #332875

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

1
Expert's answer
2022-04-24T07:03:29-0400


#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")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS