Euler Problem 1 Revisited
The other day at the Software Development Study Group in Ann Arbor, Chris Marinos was demonstrating F#, a functional programming language targeting the .NET framework. Of course, this got me thinking about programming styles in Python. So what better way to compare and contrast programming styles than with Euler problems? As you probably don’t recall, the first Euler problem is:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
The traditional approach to this might look something like the following:
def traditional_approach():
total = 0
for i in range(1,1000):
if i % 5 == 0 or i % 3 == 0:
total += i
return total
It’s not a bad approach, but there are more concise approaches. Here is my original solution using a list comprehension:
isValid = lambda x: x % 5 == 0 or x % 3 == 0
def with_list_comprehension():
filteredValues = [x for x in range(1,1000) if isValid(x)]
return sum(filteredValues)
I like list comprehensions, but this feature does introduce a lot of noise characters. If you use list comprehensions, you probably like this solution, otherwise you’re looking for something else. The next approach uses the itertools module (and the isValid lambda from the previous example).
def with_itertools():
filteredValues = itertools.ifilter(isValid, range(1,1000))
return sum(filteredValues)
This approach removes a couple of noise characters and is structured in a way familiar to most developers. My last solution uses a module called IterHelper that I proposed in a previous post. As I mentioned in that post, IterHelper sits on top of the itertools module and implements some of the recipes from the official itertools documentation. It’s largely inspired by my desire to use LINQ from both Python and IronPython. Here’s my solution to Euler Problem 1 using IterHelper:
def with_iterhelper():
return IterHelper(range(1,1000))\
.where(isValid)\
.sum()
Thanks to the Python continuation character, a backslash, I can put discreet units of functionality on their own line, making it easier for me to consume.
If you decide to download and try out IterHelper, be aware that I’m not even considering it alpha yet. It’s still very much in the R & D phase and I’m planning on changing some of the method names.