【问题标题】:Fibonacci with Python: IndexError: list index out of range斐波那契与 Python:IndexError:列表索引超出范围
【发布时间】:2019-05-15 08:20:11
【问题描述】:

我正在尝试编写一个程序来使用 Python 计算斐波那契数:

n = int(input())

def fib(n):
    a = []
    if (n <=1):
        return n
    else:
        for i in range(2, n):
            a.append(a[-1] + a[-2])
        return a[i]
print (fib(n))

但是,我无法打印出预期的结果。例如,我输入数字 8 后,弹出如下信息:

Traceback (most recent call last):
  File "fibonacci.py", line 11, in <module>
    print (fib(n))
  File "fibonacci.py", line 9, in fib
    a.append(a[-1] + a[-2])
IndexError: list index out of range

在这个过程中出了什么问题?提前致谢。

【问题讨论】:

标签: python fibonacci


【解决方案1】:

您需要使用斐波那契数列的前 2 个数字填充您的列表:

a = [0, 1]

【讨论】:

    【解决方案2】:

    -2 和-1 索引如果你没有在使用前将它们设置在“a”列表中是不可用的。

    n = int(input())
    
    def fib(n):
        a = [0, 1]
        if n <=1:
            return n
        else:
            for i in range(2, n):
                a.append(a[-1] + a[-2])
            return a[i]
    print (fib(n))
    

    【讨论】:

      【解决方案3】:

      在您的代码中进行这些更改

      n = int(input())
      
      def fib(n):
          a = [0,1]  # add these values to your array to intialize
          if (n <=1):
              return n
          else:
              for i in range(2, n):
                  a.append(a[-1] + a[-2])
          return a  # change this also so that you can get all the values returned at the same time
      
      print (fib(n))
      

      【讨论】:

        【解决方案4】:

        调用这个函数来计算任何斐波那契数列数

        def Fibonacci(n): 
            if n<0: 
                print("Incorrect input") 
        # First Fibonacci number is 0 
            elif n==0: 
                return 0
        # Second Fibonacci number is 1 
            elif n==1: 
                return 1
            else: 
                return Fibonacci(n-1)+Fibonacci(n-2)
        

        或者您可以使用这个公式作为斐波那契数列中第 n 项的公式。

        Fn = {[(√5 + 1)/2] ^ n} / √5
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-03-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-01
          • 1970-01-01
          相关资源
          最近更新 更多