Is the notation clear?
No. Do not re-assign parameters.
f0
stands for F_0 But also F_1, F_2, ... etc during different iterations of the loop.
In the same vein, the index of the calculated Fibonacci goes from 1 to n, but n goes from n to 1. It is not obvious which term in the Fibonacci are we calculating in each iteration.
How would you name the function/parameters to be more clear?
A principle of least astonishment implementation could be something along the lines of:
def fibonacci(n, f0=0, f1=1):
f = [0] * (n+1)
f[0], f[1] = f0, f1
for i in range(2, n+1):
f[i] = f[i-1] + f[i-2]
return f[n]
Which is closest to the formal definition you would encounter in a task similar to this.
Still less surprising than the original, but also closer to it:
def fibonacci(n, f0=0, f1=1):
if n == 0:
return f0
curr, prev = f1, f0
while n > 1:
curr, prev = curr + prev, curr
n -= 1
return curr
assuming prev
and curr
are familiar names to the readers, as i
, j
are.