【发布时间】:2014-03-07 03:27:30
【问题描述】:
我遇到了这个问题的解决方案,但不明白其中的几行。 n<=1 and 1 部分在fib(n) 的定义中是什么意思,更大的部分为什么在if not fib(i)%2 中不是?这怎么不意味着“如果给定的斐波那契数不是偶数,那么我们将它添加到我们的总数中”?
cache = {}
def fib(n):
cache[n] = cache.get(n, 0) or (n<=1 and 1
or fib(n-1)+fib(n-2))
return cache[n]
i = 0
n = 0
# we have to pretend the series doesn't go beyond 4 mil
while fib(i) <= (4000000):
if not fib(i) % 2:
n = n + fib(i)
i = i + 1
print n
【问题讨论】: