Project Euler asks us to find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
The Fibonacci sequence runs from 0, 1, 1, 2, 3, 5, 8,.. to infinity. Note that the example at Project Euler starts of with 1, 2, 3, ..., but because we're only interested in the even numbers this doesn't really concern us.
A python generator is a perfect mechanism to 'yield' a possibly infinite stream of values.
The 'problem' here is, that you can't use my beloved list comprehensions to iterate through an infinite generator. That's where itertools comes in.
Itertools contains a function called takewhile(predicate, iterable), which you can wrap around a generator and have it yield it's values while predicate remains True. Make the predicate a simple lambda function and you have a nice one-liner to solve this problem.
update: : As per Damjan's advice (thanks!), it's more efficient to write the list comprehension as an implicit generator comprehension like this:blog comments powered by Disqus