An iterative algorithm for Fibonacci numbers
Solution 1:
The problem is that your return y
is within the loop of your function. So after the first iteration, it will already stop and return the first value: 1. Except when n
is 0, in which case the function is made to return 0
itself, and in case n
is 1, when the for loop will not iterate even once, and no return
is being execute (hence the None
return value).
To fix this, just move the return y
outside of the loop.
Alternative implementation
Following KebertX’s example, here is a solution I would personally make in Python. Of course, if you were to process many Fibonacci values, you might even want to combine those two solutions and create a cache for the numbers.
def f(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a + b
return a
Solution 2:
You are returning a value within a loop, so the function is exiting before the value of y ever gets to be any more than 1.
If I may suggest something shorter, and much more pythonful:
def fibs(n):
fibs = [0, 1, 1]
for f in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs[n]
This will do exactly the same thing as your algorithm, but instead of creating three temporary variables, it just adds them into a list, and returns the nth fibonacci number by index.
Solution 3:
On fib(0), you're returning 0 because:
if (n == 0) {
return 0;
}
On fib(1), you're returning 1 because:
y = 1
return y
On fig(2), you're returning 1 because:
y = 1
return y
...and so on. As long as return y
is inside your loop, the function is ending on the first iteration of your for loop every time.
Here's a good solution that another user came up with: How to write the Fibonacci Sequence in Python