Python中的项目Euler#2

Python中的项目Euler#2,第1张

概述背景我坚持这个问题: 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

背景

我坚持这个问题:

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 fibseven_fibs = [] #Holds only even fibs

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

x,y = 0,1 #sets x to 0,y to 1while 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 = 0for 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 sequenceprint "\nEven Numbers: ",even_fibs #outputs even numbersprint "\nSum of Even Numbers:  ",sum(even_fibs) #outputs the sum of even numbers

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

最佳答案当序列中接下来两个值的总和大于4,000,000时,您将停止.您打算将序列中的所有值都考虑到4,000. 总结

以上是内存溢出为你收集整理的Python中的项目Euler#2全部内容,希望文章能够帮你解决Python中的项目Euler#2所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1205385.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存