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 Numbers (Python)
# 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
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Stefan_3 0 Newbie Poster
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.