from fractions import gcd print reduce(lambda x, y: (x*y)/gcd(x,y), range(1, 20), 1)
I suppose we should say:
from fractions import gcd def lcm(numbers): return reduce(lambda x, y: (x*y)/gcd(x,y), numbers, 1) print lcm((3, 4)) print lcm((3, 6)) print lcm((4, 6)) print lcm((3, 6)) print lcm(range(1, 20))
4 comments:
Hi! I think that this way of implementing the lcm is great; but what about fractional numbers? In this way, it will always return 1. So i suggest to remove the third argument of the reduce function, so thatthe lcm can be calculated properly even for numbers like 1/3 and 1/9 :)
TY! Your version is probably better as long as you want the lcm to work with rational numbers as well. Which is a good thing as I don't see any drawbacks in that.
I'm glad you like this version ;) of course it will raise an error instead of returning 1 if the sequence is empty, but all in all it's not too bad, I think
That's ok, though to keep the code more clear and reusable you'd probably write a separate function "lcm" and then use it: reduce(lcm, xs, 1).
Post a Comment