Taking on Project Euler with Python

Lately a number of posts on Project Euler, a series of predefined mathematical/computer science puzzles, have come to my attention. Bill Wagner has started a series of posts solving the Euler problems in C# and Dustin Campbell has posted one solution in F#. Several of my co-workers at SRT Solutions have been working through solutions in Ruby, Scala and Boo. My contribution will be in Python.

Project Euler problem 1 reads as follow: "Add all the natural numbers below 1000 that are multiples of 3 or 5." Python's list comprehension makes the solution to this problem trivial.

print sum([x for x in range(1,1000) if x%5==0 or x%3==0])

List comprehension is really just shorthand for a loop that sticks a variable into a sequence. In this solution, the loop is represented by the "for x in range(1,1000)" portion of the statement and a condition is added immediately following. The first "x" really just represents any value that is added to the sequence assuming it gets by our condition. Use the built-in "sum(list)" function and we have our answer. Simple, elegant and very readable.

Published Sunday, April 06, 2008 9:05 PM by dhawley
Filed under: ,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)