gpt4 book ai didi

python - Python 中的欧拉计划 #2

转载 作者:太空狗 更新时间:2023-10-30 01:16:11 25 4
gpt4 key购买 nike

背景

我被这个问题困住了:

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.

我试图找出问题是出在我的斐波那契数生成器、获取偶数的代码,还是我添加数字的方式,但都无济于事。

代码

我决定将数字存储在列表中。在这里,我创建它们。

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,000。

关于python - Python 中的欧拉计划 #2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15419722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com