Search code examples
pythonpython-3.xfractions

Create Fraction in Python


I have been given a task at school to define a function name "fraction", work just as the Fraction Modules. Here is how I do it:

def GCD(x,y):
  while y!= 0:
    (x,y) =(y,x%y)
  return x  
def fraction(a,b):
  a/=GCD(a,b)
  b/=GCD(a,b)
  print(str(int(a))+"/"+str(int(b)))

But when I tried to see how it'd work, it became like this:

fraction(45,9)
5/9

I don't know where I was wrong, can someone help me to figure it out? Thank you so much.


Solution

  • In your def fraction,

    def fraction(a,b):
      a/=GCD(a,b)
      b/=GCD(a,b)
      print(str(int(a))+"/"+str(int(b)))
    

    You modified a. a became 45/9 = 5. b divided by GCD(5,9) (which equals 1) will just be b. Instead, you could store the GCD in a temporary variable and divide both by it.

     def fraction(a,b):
      gcd = GCD(a,b)
      a//=gcd
      b//=gcd
      print(str(int(a))+"/"+str(int(b)))