Skip to content

Instantly share code, notes, and snippets.

@astex
Created June 9, 2016 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astex/60b1582a618fd4eac58ff9f4a519a363 to your computer and use it in GitHub Desktop.
Save astex/60b1582a618fd4eac58ff9f4a519a363 to your computer and use it in GitHub Desktop.

This is uncached. It has O(2^n) time complexity.

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

We can pretty easily make this O(n) by introducing a caching decorator.

def memoize(f):
    cache = {}
    def g(n):
        if n not in cache:
            cache[n] = f(n)
        return cache[n]
    return g

Now, we decorate our fib() function and it works in O(n) time (and space) complexity.

@memoize
def fib(n):
    return n if n < 2 else fib(n-1) + fib(n-2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment