Search code examples
pythonrecursionmemcachedfibonacci

Explain how to use memory caches in Python


I have the following recursive solution for the nth fibonacci number:

def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

x=input('which fibonnaci do you want?')
print fib(x)

I need to change this, so that it uses a stored memory cache and gets stuff out of that to speed up the process. I really don't know how to do this and google isn't helping.


Solution

  • This is not the most elegant solution, but will help you learn how this works.

    import memcache
    
    def fib(n):
        v = mc.get(str(n))
        if not v is None:
            print "Hit on cache: %s = %s" %(n, v)
            return v
    
        print "Miss on cache"
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            v = fib(n-1) + fib(n-2)
            mc.set(str(n), v)
            return v
    
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)
    x=input('which fibonnaci do you want?')
    print fib(x)
    

    If you are on Ubuntu: sudo apt-get install python-memcache to run this code