I am trying to solve Project Euler problem 2 in Python, and decided on a strategy based on iterables.
Here is the generator for the Fibonacci sequence,
def fnFibonacci():
fibNumPrev, fibNumCurrent = 0, 1
while True:
yield fibNumCurrent
fibNumPrev, fibNumCurrent = fibNumCurrent, fibNumCurrent + fibNumPrev
When I try to filter out the Fibonacci numbers that are less than 4 million and divisible by 2, it doesn't work, filtering everything out:
sum(list(itertools.takewhile(lambda x: x < 4e6 and x % 2 == 0 , fnFibonacci())))
However, both this (which ignores the evenness condition):
sum(list(itertools.takewhile(lambda x: x < 4e6, fnFibonacci())))
and this list comprehension:
sum([fibNum for fibNum in list(itertools.takewhile(lambda x: x < 4e6, fnFibonacci())) if fibNum % 2 == 0])
work. Can't really tell what's going on.