Python中的项目Euler#2

前端之家收集整理的这篇文章主要介绍了Python中的项目Euler#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,…

By considering the terms in the Fibonacci sequence whose values do not exceed four million,find the sum of the even-valued terms.

我试图发现问题是我的Fibonacci数字生成器,获取偶数的代码,甚至我添加数字无效的方式.

我决定将这些数字存储在列表中.在这里,我创造了它们.

list_of_numbers = [] #Holds all the fibs
even_fibs = [] #Holds only even fibs

然后,我创建了我的发电机.这是一个潜在的问题领域.

x,y = 0,1 #sets x to 0,y to 1
while x+y <= 4000000: #Gets numbers till 4 million
    list_of_numbers.append(y)
    x,y = y,x+y #updates the fib sequence

然后,我创建了一些代码来检查数字是否是偶数,然后将其添加到even_fibs列表中.这是代码中的另一个弱点.

coord = 0
for number in range(len(list_of_numbers)):
    test_number = list_of_numbers [coord]

    if (test_number % 2) == 0:
        even_fibs.append(test_number)
    coord+=1

最后,我显示信息.

print "Normal:  ",list_of_numbers #outputs full sequence
print "\nEven Numbers: ",even_fibs #outputs even numbers
print "\nSum of Even Numbers:  ",sum(even_fibs) #outputs the sum of even numbers

我知道这是一个提出问题的可怕方式,但出了什么问题?请不要给我答案 – 只需指出有问题的部分.

最佳答案
当序列中接下来两个值的总和大于4,000,000时,您将停止.您打算将序列中的所有值都考虑到4,000.
原文链接:https://www.f2er.com/python/439493.html

猜你在找的Python相关文章