Memoization In Python

last modified: October 22, 2009

Below is an implementation of MemoIzation written in PythonLanguage. Is this technique possible or even applicable in OO languages like Java? -- AdewaleOshineye


#!/usr/bin/python

"""Take a function f and return a function fm that is the same as f except it uses cacheing. Uses Python 2.2
Author: AdewaleOshineye 
"""
import time

def memoize(f):
        cache = {},
        def fm(*args):
                if args not in cache:
                        cache[args] = f(*args)
                return cache[args]
        return fm

def test(function, arguments, iterations):
        startTime = time.time()
        for x in range(iterations):
                result = function(*arguments)
        endTime = time.time()
        print "Result is ", result
        return endTime - startTime

if __name__=='__main__':
        TEST_ITERATIONS = 1000000
        def factorial(n):
                if n > 1:
                        return n * factorial(n-1)
                else:
                        return 1

        def intersperse(arg1, arg2):
                return arg1.join(arg2)

        factorial2 = memoize(factorial)
        intersperse2 = memoize(intersperse)

        functions = [intersperse, intersperse2, factorial, factorial2]
        arguments = [("|", "HelloWorld"),("|", "HelloWorld"),(10,),(10,)]
        index = 0
        for f in functions:
                print "Testing %s took %.3f seconds" % (f.__name__, test(f, arguments[index], TEST_ITERATIONS))
                index += 1

Implementations in other languages are desired.


Loading...