2010-01-15 44 views
0

有人可以告诉我为什么这应该是错的吗?与Python的欧拉项目2号

#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

当您尝试运行它时,会出现什么问题?你得到一个错误的结果?你有错误吗? – Wesley 2010-01-15 20:37:59

+0

我也读过这个问题(但以不同的方式):http://stackoverflow.com/questions/736495/haskell-script-running-out-of-space – 2010-01-15 20:42:45

+0

顺便说一句,前两个斐波纳契数字都是1 ...但当然,这并不影响偶数项的总和。 :) – 2010-01-15 22:15:04

回答

6

if a > 4000000: 
     break 
    sum += a 
    print('sum', sum) 

你应该比较替换

sum += a 
    print('sum', sum) 
    if sum >= 4000000: 
     break 

“一” 与400万,而不是 “和”,像丹尼尔·罗斯曼说。

2

该问题要求的总和甚至条款其中不超过四百万。您正在检查总和是否不超过4米。

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 

所以你的代码,即使它是错的(见其他答案)恰好给出了正确的答案。

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 

我敢肯定这很简单......谢谢!

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

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