2010-01-15 41 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