Reputation: 11
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.
Upvotes: 0
Views: 110
Reputation: 46859
you modify a
before you calculate the GCD
for b
; your second GCD
calculation will therefore always return 1
.
you could try this:
def fraction(a,b):
g = GCD(a,b)
a //= g
b //= g
print("{}/{}".format(a, b))
also note that i used integer division (floordiv) //
so i do not get a float as result that i have to cast back to in int
.
Upvotes: 2
Reputation: 11
Thank you so much for your helpful answers, I've realized what I did wrong and make a new one combining all your answers. Here is the new one:
def GCD(x,y):
while y!= 0:
(x,y) =(y,x%y)
return x
def fraction(a,b):
gcd=GCD(a,b)
a=a//gcd
b=b//gcd
print(str(a)+"/"+str(b))
Thank you all so so much again, you have made my day.
Upvotes: 0
Reputation: 1527
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)))
Upvotes: 0