Monday, September 6, 2010

Nice functional LCM in Python

I was putting order in my hard disk when I stumbled on this:

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:

Antonio said...

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 :)

Unknown said...

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.

Antonio said...

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

tokland said...

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).