Fibonacci sequence program in python working fine except for input 0 -


this program showing correct output except input n=0.

def fib(n):     f=list()     i=0     while(i<=n):         f.append(i)         i+=1     f[0]=0     f[1]=1     in range(2,n+1):         f[i]=f[i-1]+f[i-2]         i+=1     return f[n] n=int(input()) print(fib(n)) 

when give input n=0, shows following error:

traceback (most recent call last):     file "fib.py", line 16, in <module>         print(fib(n))     file "fib.py", line 10, in fib         f[1]=1     indexerror: list assignment index out of range 

two lines in middle not necessary due initializing elements during while loop. , error comes fact, n=0, adding 1 elemnt list. , after changing value of first , second element. there no second element.

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

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -