Home > python > Fibonacci numbers

Fibonacci numbers


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.


#!/usr/bin/env python

# fibonacci.py

def fib(n):
    assert(n >= 0)
    li = []
    a, b = 0, 1
    for i in range(n+1):
        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.

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

Categories: python Tags: ,
  1. No comments yet.
  1. October 19, 2010 at 16:03

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: