Friday, December 3, 2010

Number Two

Python shines on this one. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.


from itertools import ifilterfalse

def fib(n1=1,n2=1,fmax=4000000):
"terminating fibonacci sequence"

assert 0 < n1 <= n2 < fmax
l = [n2,n1]
while l:
if l[0] < fmax/2:
l.append(sum(l))
yield l.pop(0)

if __name__ == "__main__":
print sum(ifilterfalse(lambda x: x % 2,fib()))

No comments: