[英]By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms
[英]Even valued terms sum in fibonacci, limit is 4 million
def fib(n):
if n<= 1:
return n
else:
return(fib(n-1)+fib(n-2))
def comp():
L=[]
for i in range(1,4000000):
if i % 2 ==0:
L.append(fib(i))
return sum(L)
print(comp())
這段代碼有什么問題? 它沒有返回任何東西,但在我看來它看起來不錯。
return
語句設置為錯誤的增量。 它在第一次i % 2 == 0
變為真時執行(在您的情況下為 i == 2 )。
def fib(n):
if n<= 1:
return n
else:
return(fib(n-1)+fib(n-2))
def comp():
L=[]
for i in range(1,4000000):
if i % 2 ==0:
L.append(fib(i))
return sum(L)
print(comp())
但是,上面的代碼不起作用。 你知道這個數字會有多大嗎?
嘗試
for i in range(1,40):
作為開始。 在我的機器上花了好幾秒鍾。 結果是 63245985。
你應該從函數而不是 for 循環中返回sum(L)
按照下面的代碼
def fib(n):
if n<= 1:
return n
else:
return(fib(n-1)+fib(n-2))
def comp():
L=[]
for i in range(1,20):
if i % 2 ==0:
L.append(fib(i))
return sum(L)
print(comp())
和其他事情看范圍太多,因為這會花費一些時間或可能會產生任何與內存相關的錯誤,因此請減少它以進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.