Python fabonacci implementations.

Regular with recursion

def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

One-liner with recursion

f = lambda n: n if n < 2 else f(n-1) + f(n-2)

Sequence generator

def fib(n):
    a, b = 0, 1
    for _ in xrange(n):
        yield a
        a, b = b, a + b

Sequence printer

def fib(n):
    a, b = 0, 1
    for _ in xrange(n):
        print a,
        a, b = b, a + b

References

BACK TO TOP
Post tagged with: python, algorithm