你好 Seamonkey,欢迎来到 SO。我很高兴你在这个问题上比上一个问题付出了更多的努力:)
我将与您一起逐步完成代码。对于简单的问题,我发现不使用函数会更容易,因为当必须处理全局变量时它们会很烦人
#This part of the code gets the entire fibonacci sequence
list_of_numbers = []
even_fibs = []
x,y = 0,1 #sets x to 0, y to 1
while y <= 4000000: #Gets numbers till 4 million
list_of_numbers.append(y)
x, y = y, x+y #updates the fib sequence
在这段代码中,(如果您愿意,可以将其更改为函数),我们计算完整的斐波那契数列,最多 400 万。我们还创建了两个列表,list_of_numbers
和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
在这里,我测试了列表中的数字是否list_of_numbers
是偶数。如果是,我将它们添加到even_fibs
列表中。您可以在此处阅读列表。
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
这只是输出了我们的发现。
由于您似乎喜欢函数,因此我在此处添加了代码。解释和上面的一样。
#This part of the code gets the entire fibonacci sequence
list_of_numbers = []
even_fibs = []
def fib(list_of_numbers):
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
return list_of_numbers
def even(list_of_numbers, 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
return even_fibs
fib(list_of_numbers) #call fib function
even(list_of_numbers, even_fibs) #Call the even function
#Output
print "Normal: ", list_of_numbers
print "\nEven Numbers: ", even_fibs
print "\nSum of Even Numbers: ", sum(even_fibs)