該解決方案可能相當簡單,但我無法弄清楚。這是代碼,它是一個簡單的斐波那契數字生成器。目標是總結所有甚至低於4,000,000的斐波納契數。Python:與模運算符的奇行爲
我的做法是,先產生低於400萬的所有Fibonacci數,然後或者: 一)產生一個新的列表(「偶」)與甚至是那些(這工作正常) b)除去從奇數的人list「all」
但是,在後一種情況下,出於我不明白的原因,這: [2,5,8,21,34,89,144,377,610,1597 ,2584,6765,10946,28657,46368,121393,196418,514229,832040,2178309,3524578]
任何幫助,非常感謝。謝謝!
all = []
even = []
def fibonacci():
a, b = 1, 2
while a < 4000000:
all.append(a)
a, b = b, a + b
print all
##Putting all the even fibonacci numbers in a different list and summing them up works fine
# for i in all:
# if i % 2 == 0:
# even.append(i)
# print even
# print sum(even)
# But for some strange reason I can't figure out how to remove the odd numbers from the list
for i in all:
if i % 2 != 0:
all.remove(i)
print all
print sum(all)
fibonacci()
我建議你不要使用「全部」作爲變量名。有一個非常有用的內建函數叫做[all](http://docs.python.org/library/functions.html#all),它非常方便。 – DSM 2012-03-13 19:35:39
帝斯曼,感謝您指出這一點! – talkinghead 2012-03-13 20:52:48
此外,如果有人對斐波納契序列有所瞭解:是的,它通常以0,1,1,2,...開頭,但是對於這個問題的歐拉項目說明書已經以1,2,..., – talkinghead 2012-03-13 21:00:34