【问题标题】:What is the problem about my fibonacci python code?我的斐波那契 python 代码有什么问题?
【发布时间】:2019-10-19 19:47:23
【问题描述】:

如果你能看看我的代码。

numbers = [1,2]
times = int(input("How many numbersM (minimum is 2)"))
def fibonacci(numbers, times):
    for i in range(0, times):
        for j in numbers:
            numbers.append( numbers[j] + numbers[j+1])
        print(numbers[i])
fibonacci(numbers, times)

【问题讨论】:

  • 你告诉我们,你得到了什么错误或输出,你期望什么?
  • 只要把for j in numbers改成for j in range(len(numbers))就OK了。
  • @finefoot,哦,你是对的。我刚刚看到他/她错误地将for i in L 作为索引,所以只是评论指出你应该做索引你应该做for i in range(len(L))

标签: python fibonacci


【解决方案1】:

如果你这样运行你的代码,你会得到

IndexError: list index out of range

因为for j in numbers:numbers 中的值的循环,其中包含值1,当您尝试访问numbers[j+1] 时,这是一个超出范围的索引,因为此时没有numbers[2]。为什么你还需要第二个for 循环呢?您将使用numbers[i]numbers[i+1] 访问最后一个和倒数第二个值。无需遍历列表的其他值。

我已经删除了那个循环,如果你像这样运行你的代码:

numbers = [1,2]
times = int(input("How many numbersM (minimum is 2)"))
def fibonacci(numbers, times):
    for i in range(0, times):
        numbers.append( numbers[i] + numbers[i+1])
        print(numbers[i])
fibonacci(numbers, times)

你会得到这样的东西,例如:

How many numbersM (minimum is 2)5
1
2
3
5
8

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2012-03-02
    • 1970-01-01
    • 2012-12-29
    • 2011-09-30
    相关资源
    最近更新 更多