So I was just modifying something I felt that fit my style a bit better from an answer to an algorithm from another person. One of the things I decided to change, and at the time not confused at all about, is changing all the places where they placed a //
with an int()
surrounding the whole calculation, giving me the same result. Now, when I finished changing all these minor details, I thought the test cases would pass...I was wrong. The functions below are supposed to do the same thing, which is returning all the given fractions (in a format of...for example[[1, 2], [1, 3], [1, 4]]
) with the same common denominator, if the given example was to go through the function it should return [[6, 12], [4, 12], [3, 12]]
.
Using int()
for the return (last bit):
from math import gcd
from functools import reduce
def convertFracts(lst):
if not lst: return []
lcm = lambda a, b: int(a*b / gcd(a, b))
denom_list = (i[1] for i in lst)
lcm_num = reduce(lcm, denom_list)
return [[int(i[0]*lcm_num / i[1]), lcm_num] for i in lst]
Using //
for the return (last bit):
from math import gcd
from functools import reduce
def convertFracts(lst):
if not lst: return []
lcm = lambda a, b: int(a*b / gcd(a, b))
denom_list = (i[1] for i in lst)
lcm_num = reduce(lcm, denom_list)
return [[i[0]*lcm_num // i[1], lcm_num] for i in lst]
The test case that failed when using int()
but passed when using //
which contained really large fractions:
[[27115, 5262], [87546, 11111111], [43216, 255689]]
This is how it came out when using the int()
:
[[77033412951888080, 14949283383840498], [117787497858828, 14949283383840498], [2526695441399712, 14949283383840498]]
But it wasn't equal to the correct answer which was:
[[77033412951888085, 14949283383840498], [117787497858828, 14949283383840498], [2526695441399712, 14949283383840498]]
When using //
instead of int()
for the return bit, it passed...my question is, why did int()
fail at what //
didn't, is it less accurate with bigger numbers?