Below is an iterative calculation of Fibonacci Sequence.
def fibonacci(n):
if n < 0:
raise ValueError("invalid index!")
if n==0:
return 0
if n==1:
return 1
f = [0,1]
for i in range(2,n+1):
f.append(f[i-1] + f[i-2])
return f[n]
As it is, the list f
is a local variable inside the function and will be recreated and repopulated each time the fibonacci
function is called.
How could this code snippet be rewritten so that Python would not need to recalculate fibonacci(5)
once it was called and could use it the next time fibonacci(5)
or above was called? I know global variable is one option but what would be the most "Pythonic" way of doing this?