A bit late to the game, I started doing the Project Euler puzzles. The first one was quite simple: find the sum of all the multiples of 3 or 5 below 1000.

Ths can be solved with a single python one-liner, using a list comprehension.

sum([i for i in range(1000) if i%3==0 or i%5==0])

I've become a big fan of list comprehensions and use them as much as possible, though I must admit there are situations where a more verbose version is more readable.

update: : As per Jason's advice (thanks!), it's more efficient to use xrange instead of range and write the list comprehension as an implicit generator comprehension like this:

sum(i for i in xrange(1000) if i%3==0 or i%5==0)
blog comments powered by Disqus