Wednesday, September 17, 2008

Problem 2: Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million


'''
Problem 2
19 October 2001

Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
Solution: Stephen C. Murphy, September 17, 2008
I had just seen a fibonacci function in the Python Primer so I just modified
that function slightly to return a list. My original solution didn't include
a list comprehension, but now I'm a bit addicted to them so I couldn't resist.
'''
def fib(n):
soln = []
a, b = 0, 1
while b < n:
soln.append(b)
a, b = b, a+b
return soln

print sum([i for i in fib(4000001) if i % 2 == 0])

No comments: