.

Project Euler problem 1

To start off the new blogging adventure, i'll post a little bit of code.

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.

print "the answer is", 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:

print "the answer is", sum(i for i in xrange(1000) if i%3==0 or i%5==0)

posted on 25 Nov, 2008 to Python, Project Euler » view comments
blog comments powered by Disqus