list - Getting an index error in a python fibonacci program -
i started "algorithmic toolbox" on coursera, , writing version of fibonacci program in python 2.7
def fibonacci(n): f = [] f[0] = 0 f[1] = 1 in range(0,n): f[i] = f[i-1] + f[i-2] return f[n] fibonacci(3)
but, keep getting error:
traceback (most recent call last): file "fibonacci.py", line 11, in <module> fibonacci(3) file "fibonacci.py", line 3, in fibonacci f[0] = 0 indexerror: list assignment index out of range
you can't create new elements in python list assigning non-existing indices. list empty, indices 0
, 1
don't exist.
use list.append()
instead:
def fibonacci(n): f = [0, 1] # list 2 initial elements in range(2, n + 1): f.append(f[i-1] + f[i-2]) # add new value list return f[n]
note loop starts @ 2
, not 0
, because have values 0
, 1
. stop argument range()
not included if want find n
th fibonacci number, need run range n + 1
.
now code works:
>>> def fibonacci(n): ... f = [0, 1] ... in range(2, n + 1): ... f.append(f[i-1] + f[i-2]) ... return f[n] ... >>> fibonacci(10) 55
note don't need store values in list; need track last 2. use 2 variables , swap these around each iteration; 1 stores
def fibonacci(n): prev, curr = 0, 1 # 2 variables, 1 set 0, other 1 _ in range(n - 1): # run n - 2 times prev, curr = curr, prev + curr return curr
note doesn't boundary tests on n
, n = 0
result going incorrect (1 returned rather 0). remedied if n < 1: return 0
line @ top.
Comments
Post a Comment