I am trying to print fibonacci series using lists in python. This is my code
f=[1,1]
for i in range(8):
f.append(f[i-1]+f[i-2])
print(f)
output is
[1, 1, 2, 3, 2, 3, 5, 5, 5, 8]
I am not getting the bug here!
Python's range starts at 0, you need to start with generating element 2. By starting at 0, you get negative indices for the first couple of calculations, which access from the end of the list. To fix this, change the loop to for i in range(2, 8).
To clarify what seems to be a source of confusion, by starting the range at zero and using negative indexing you end up with the following terms being summed and appended to the list:
f[2] = f[0-1] + f[0-2] = f[-1] + f[-2] (= f[1] + f[0]) = 1 + 1 = 2 # looking good
f[3] = f[1-1] + f[1-2] = f[0] + f[-1] (= f[0] + f[2]) = 1 + 2 = 3 # looking good
f[4] = f[2-1] + f[2-2] = f[1] + f[0] = 1 + 1 = 2 # oops!
f[5] = f[3-1] + f[3-2] = f[2] + f[1] = 2 + 1 = 3
From that point on the numbers are on track, but offset from the proper indexing by 2.
f.append(f[-1] + f[-2]) regardless of the range limits.f[-1] + f[-2] sums the two last elements.range statement. It repeats summing the first couple of elements. That's why it incorrectly repeats "2, 3, 2, 3".f.append(f[-1] + f[-2]) is still correct. It doesn't even refer to i.f=[1,1]
for i in range(8):
f.append(f[i]+f[i+1])
print(f)
RESULT
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
You should be aware that the range function starts at 0 if you don't explicitly specify a starting point. In your case, it should be: for i in range(2, 8).
Output:
[1, 1, 2, 3, 5, 8, 13, 21]
Also, in Python, you can use negative index in an array to count from the right instead of the left, this is why you had this weird result.
Script
f=[1,1]
for i in range(2,8):
print(i)
f.append(f[i-1]+f[i-2])
print(f)
Output
2
[1, 1, 2]
3
[1, 1, 2, 3]
4
[1, 1, 2, 3, 5]
5
[1, 1, 2, 3, 5, 8]
6
[1, 1, 2, 3, 5, 8, 13]
7
[1, 1, 2, 3, 5, 8, 13, 21]
Issue is i starts from 0, f[-1], f[-2] returns 0.
start using range from 2 and 8 represents first 8 fibonacci numbers.
removing debug print
Script
f=[1,1]
for i in range(2,8):
f.append(f[i-1]+f[i-2])
print(f)
i,f,f[i-1], andf[i-2]are on each step.i=2- you've already appended to the list twice, but the next value you append isf[0] + f[1]range(2, 8)