python fibonacci数列的bottonup算法

ycl3bljg  于 2023-05-05  发布在  Python
关注(0)|答案(2)|浏览(76)

例外情况:

C:\Users\Wandres\venv\insertionsort\Scripts\python.exe C:/Users/Wandres/PycharmProjects/insertionsort/fibobottomup.py
Traceback (most recent call last):
  File "C:\Users\Wandres\PycharmProjects\insertionsort\fibobottomup.py", line 13, in <module>
    print(fibbottonup(5))
  File "C:\Users\Wandres\PycharmProjects\insertionsort\fibobottomup.py", line 8, in fibbottonup
    f=fib[k-1]+fib[k-2]
KeyError: 0

还有密码

def fibbottonup (n):  
    fib = {}     
    for  k in range (1, n + 1):    
        if k<2:       
           f=1            
           fib[k]=f        
        else:             
           f=fib[k-1] + fib[k-2]            
           fib[k]=f     
    return fib[n]

我正在学习动态规划,所以我试图使用的理论,我想添加数组中的斐波那契序列的每一个元素“fib”。我不知道错在哪里。

gg0vcinb

gg0vcinb1#

def fibbottonup (n):  
    fib = [0, 1]   
    for i in range (n-1):    
        fib.append(fib[i] + fib[i+1])
    return fib[n]

它是代码和解释是:ibonacci序列的前两项是0,1之后,它开始在两个元素之前求和,以找到所有元素的当前元素。所以我做了。

uajslkp6

uajslkp62#

错误在于,对于k=2,代码访问fib[k-2] = fib[0],但密钥0从未添加到fib

相关问题