0

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.

4

1 回答 1

5

itertools.takewhile当它找到第一个不符合条件的值时停止。由于第一个数字是 1 并且不能被 2 整除,它立即停止。

你可以这样写:

 sum(x for x in itertools.takewhile(lambda n: n < 4e6, fnFibonacci()) 
                if x % 2 == 0)
于 2013-10-02T14:57:26.190 回答