Home > python > Fibonacci numbers

Fibonacci numbers

Exercise

Now an easy one. Calculate the first N Fibonacci numbers, where F0 = 0, F1 = 1, …, Fn = Fn-1 + Fn-2. Write a function that receives N as a parameter and returns a list with the first N Fibonacci numbers. Example: fib(10) would produce [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]. Notice that F0 = 0 is included in the result.

Solution

#!/usr/bin/env python

# fibonacci.py

def fib(n):
    assert(n >= 0)
    li = []
    a, b = 0, 1
    for i in range(n+1):
        li.append(a)
        a, b = b, a+b
    return li
            
if __name__ == "__main__":
    print fib(10)

Here we solved the problem in an iterative way, but you can do it with recursive calls too.

Links
See http://www.scriptol.com/programming/fibonacci.php for a comprehensive list how to implement it in any language.

Categories: python Tags: ,
Design a site like this with WordPress.com
Get started