Gra*_*ant 4 python fibonacci while-loop
我正在解决项目欧拉问题,如下所示:
通过考虑Fibonacci序列中的值不超过四百万的项,找到偶数项的总和."
所以我使用这个脚本来打印斐波那契序列高达四百万:
a = 0
b = 1
while b < 4000000:
print b
a, b = b, a+b
Run Code Online (Sandbox Code Playgroud)
显然,我可以运行它,只需手动添加偶数值,但我觉得我在欺骗.
从技术上讲,我想我要问两个问题:
哦,我确信它非常明显,但我很新......好吧,编程一般而且我很容易迷失在专家的冗长中.提前致谢!
如果你反对变量赋值,你可能会喜欢一种功能方法:
>>> from itertools import takewhile, ifilter
>>> def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
>>> def is_even(x):
return x % 2 == 0
>>> sum(ifilter(is_even, (takewhile(lambda x: x<4000000, fib()))))
4613732
Run Code Online (Sandbox Code Playgroud)