Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubleshooting Fibonacci series with python

I am reading a textbook and I have no idea why is this code compiling differently on my compiler than what it says in the book.

def fibs(number):
    result = [0, 1]
        for i in range(number-2):
            result.append(result[-2] + result[-1])
        return result

So this: fibs(10) should give me [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] but for some reason I get [0, 1, 1] for every number that I pass in to the function.

Any ideas?

like image 757
bobek Avatar asked May 20 '26 15:05

bobek


2 Answers

The code in your post isn't valid Python. Since your code was able to run, it's probably actually like this:

def fibs(number):
    result = [0, 1]
    for i in range(number-2):
        result.append(result[-2] + result[-1])
        return result

Your return result is indented such that it's inside the for loop, instead of below it. This will cause it to only add one value to the list before returning, producing the list you see.

Unindent that line and it should work properly.

like image 152
Jeremy Avatar answered May 23 '26 05:05

Jeremy


In Python, indentation is of primary importance. The code you have posted is incorrectly indented.

>>> def fibs(number):
...     result = [0, 1]
...     for i in range(number-2):
...         result.append(result[-2] + result[-1])
...     return result
...
>>> fibs(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
like image 37
Johnsyweb Avatar answered May 23 '26 04:05

Johnsyweb