Reputation: 10984
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.
Upvotes: 0
Views: 315
Reputation: 107746
itertools.takewhile
stops when it finds the first value that does not match the criterion. Since the first number is 1 and not divisible by 2 it stops immediately.
You can write this:
sum(x for x in itertools.takewhile(lambda n: n < 4e6, fnFibonacci())
if x % 2 == 0)
Upvotes: 5