Fibonacci Numbers (Python)

vegaseat 1 Tallied Votes 2K Views Share

The Fibonacci series of numbers was used by Leonardo of Pisa, a.k.a. Fibonacci (around the year 1200), to describe the growth of a rabbit population. The series has been noted to appear in biological settings, such as the branching patterns of leaves in grasses and flowers. We take a look at two different ways Python can get you these numbers. The generator function will add the next number to the series each time it is called. The recursive function gives the Fabonacci value for the parameter given.

# Fibonacci number series
# tested with Python24       vegaseat      18oct2005

def fibonacci():
    """a generator for Fibonacci numbers, goes to next number in series on each call"""
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

f = fibonacci()
for x in range(13):
    print f.next(),  # 0 1 1 2 3 5 8 13 21 34 55 89 144

print
    
def fibo(n):
    """
    use recursion to get Fibonacci numbers, returns the Fibonacci value for n
    not very efficient because of the many function calls
    """
    if n < 2:
        return n
    else:
        return fibo(n - 1) + fibo(n - 2)

for x in range(13):
    print "fibo(%d) = %d" % (x, fibo(x))
    
print
print "Calculating ..."
print

print "fibo(%d) = %d" % (30, fibo(30))  # this takes a moment!
Yuyiya 0 Newbie Poster

Those interested in seeing a variety of algorithms to solve a given task will find eight distinct approaches, three of them specifically aimed at performing "Quick exact computation of large individual Fibonacci numbers", and all implemented in Python, at the Literate Programming page: Fibonacci_numbers_(Python).

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Thanks Yuyiya for the nice information.

If you want to use the Fibonacci generator function, you can apply Python module itertools to get selected parts of the series ...

# using itertools.islice(iterable, [start,] stop [, step])
# to get selected results of the Fibonacci generator function

from itertools import islice

def xfibo():
    """
    a generator for Fibonacci numbers,
    goes to next number in series on each call
    """
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print("show Fibonacci series for n = 200 to 210:")
for k in islice(xfibo(), 200, 211):
    print(k)

print('-' * 50)

print("show Fibonacci number for n = 210:")
for k in islice(xfibo(), 210, 211):
    print(k)

"""my result (Python2 or Python3) -->
show Fibonacci series for n = 200 to 210:
280571172992510140037611932413038677189525
453973694165307953197296969697410619233826
734544867157818093234908902110449296423351
1188518561323126046432205871807859915657177
1923063428480944139667114773918309212080528
3111581989804070186099320645726169127737705
5034645418285014325766435419644478339818233
8146227408089084511865756065370647467555938
13180872826374098837632191485015125807374171
21327100234463183349497947550385773274930109
34507973060837282187130139035400899082304280
--------------------------------------------------
show Fibonacci number for n = 210:
34507973060837282187130139035400899082304280
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a mild update ...

''' fibonacci23.py
modified to work with Python273 and Python3x
notice that f.next() has changed to next(f)
'''

# allows Python273 to use Python3 style print() options
from __future__ import print_function

def fibonacci():
    """a generator for Fibonacci numbers, goes to next number in series on each call"""
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

f = fibonacci()
for x in range(13):
    print(next(f), end=" ")

''' output ...
0 1 1 2 3 5 8 13 21 34 55 89 144
'''
Stefan_3 0 Newbie Poster

One of the fastest ways to produce fibonaccis is with a matrix. The given code here produces the first 1000 fibs in a flash of a second:

f=[1]+[0]+[1]
for i in xrange(1000):
    f[-1]=sum(f[:-1])
    f[:-1]=f[1:]
    print f[0],
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.