有人可以告诉我为什么这应该是错的吗?
#Each new term in the Fibonacci sequence is generated
#by adding the previous two terms. By starting with 1 and 2,
#the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#Find the sum of all the even-valued terms in the sequence
#which do not exceed four million.
sum=2
list = [1,2]
for x in range(2,100):
a = list[x-2]+list[x-1]
print(a)
list.append(a)
if a % 2 == 0:
sum += a
print('sum', sum)
if sum >= 4000000:
break
答案 0 :(得分:7)
这是使用生成器和itertools解决问题的完全不同的方法:
def fib():
a = b = 1
while 1:
yield a
a, b = b, a + b
import itertools
print sum(n for n in itertools.takewhile(
lambda x: x <= 4000000, fib()) if n % 2 == 0)
输出:
4613732
因此,即使错误(请参阅其他答案),您的代码也会给出正确答案。
答案 1 :(得分:6)
替换
sum += a
print('sum', sum)
if sum >= 4000000:
break
带
if a > 4000000:
break
sum += a
print('sum', sum)
你应该比较“a”和4000000,而不是“和”,就像Daniel Roseman说的那样。
答案 2 :(得分:2)
问题是甚至条款的总和不超过四百万。您正在检查总和是否不超过4米。
答案 3 :(得分:0)
我正在尝试解决同样的问题 - 虽然我理解这样做的逻辑,但我不明白为什么这样做(输出正确的总和)
limit = 4000000
s = 0
l = [1,2]
while l[-1]<limit:
n = l[-1]+l[-2]
l.append(n)
print n
然后,当我放入模数函数时,它根本不输出任何东西。
limit = 4000000
s = 0
l = [1,2]
while l[-1]<limit:
n = l[-1]+l[-2]
if n % 2 == 0 :
l.append(n)
print n
我确信这很简单......谢谢!
答案 4 :(得分:0)
这是我使用的代码。它非常有用,并教你生成器。
def fib():
x,y = 0,1
while True:
yield x
x,y = y, x+y
def even(seq):
for number in seq:
if not number % 2:
yield number
def under_a_million(seq):
for number in seq:
if number > 4000000:
break
yield number
print sum(even(under_a_million(fib())))
-M1K3
答案 5 :(得分:0)
保持简单,它应该少于0.1秒。
from datetime import datetime
x, y = 1, 1
total = 0
for i in xrange (1, 100):
x = x + y
if x % 2 == 0 and x <= 4000000:
total += x
y = y + x
if y % 2 == 0 and x <= 4000000:
total += y
print total
starttime = datetime.now()
print datetime.now() - starttime