Fibonacci in Python

Here's some python code to define a fibonacci sequence in python two ways: recursively and then non-recursively. The reason to write this non-recursively is that due to the nature of this sequence - in which the next result relies on the previous results - we end up making A LOT of redundant computations.

This code is based on Udacity's CS101 programming in Python course. The Fibonacci sequence can best be understood as the golden rectangle and has been seen in Greek architecture, flowers and perhaps most famously in Leonardo's Mona Lisa and Vitruvian man.

[sourcecode language="python"]

recursive fibonacci definition

def fibonacci(n): if n < 2: return n else: return fibonacci(n-2) + fibonacci(n-1) [/sourcecode]

Let's now write this in a way that computes faster. Why should it be faster? Because the number of computations in the previous code is many. How many? Well it turns out to be exactly the number of fibonacci sequences, n.

[sourcecode language="python"] #faster fibonacci since this is NOT recursive def fibonacci(n): current = 0 after = 1 for i in range(0,n): current, after = after, current + after return current

[/sourcecode]

And now the fun part. If bunnies (at 2kg/bunny) could multiply (and never die!) in Fibonacci fashion how long until they exceed the mass of earth? That is, how many cycles of bunny procreation would it take before they outweigh our fair planet.

[sourcecode language="python"] #how long until mass of rabbits exceeds mass of earth? mass_of_earth = 5.9722 * 10**24 # in kilos mass_of_rabbit = 2 # 2 kg per rabbits

n = 1 while fibonacci(n)*mass_of_rabbit < mass_of_earth: n = n + 1 print n, fibonacci(n) [/sourcecode]

. . . Turns out the answer is 119.

Get notified about new posts