Project Euler Problem 2

Problem number 2 reads "Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million." The resolution to this problem is not quite as simple as the previous one, but it's not far off.

def fib(maxFibNumber):
    a, b = 0, 1
    while a < maxFibNumber:
        if (a % 2 == 0):
            yield a
        a, b = b, a + b

print sum([x for x in fib(4000000)])

This time we can't rely entirely on list comprehension for the answer. We have to define the fib(maxfibnumber) function that will calculate our Fibonacci sequence and return only even those that are even. I modified a Fibonacci function I found at literateprograms.org to do the job. I have to mention one of the little niceties that makes Python so useable: multiple assignment. Multiple assignment describes the technique of assigning - *binding* in Python - two variables simultaneously. We bind "a" and "b" as soon as we enter the "fib" function and then rebind them at the end of the while loop. This is just another way Python can help us with a simple programming idiom.

Published Saturday, April 12, 2008 9:02 AM by dhawley
Filed under: ,

Comments

No Comments

Leave a Comment

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