Saturday, April 7, 2012

Python & Fibonacci

A lot of people in the class I'm taking are doing a simple Fibonacci function for the first assignment but I decided that the Fibonacci function should not return a single value but instead return a map of the Fibonacci sequence up to the number passed to the Fibonacci function. I found this to be quite a challenge!
m = {}
def fib(x):
    if x == 1:
        m[0] = 0
        m[1] = 1
        return m
    if len(m) != x + 1:
        fib(x - 1)
    m[x] = m[x - 1] + m[x - 2]
    return m;

m = {}
print "fib(2) =", fib(2)
m = {}
print "fib(3) =", fib(3)
m = {}
print "fib(4) =", fib(4)
m = {}
print "fib(7) =", fib(7)
fib(2) = {0: 0, 1: 1, 2: 1}
fib(3) = {0: 0, 1: 1, 2: 1, 3: 2}
fib(4) = {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}
fib(7) = {0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13}