Pages

Monday, May 23, 2016

Memoization in Python

# -*- coding: utf-8 -*-
"""


File name: fib_mem.py

Created on Mon May 23 14:50:39 2016


Source: MITx: 6.00x Introduction to Computer Science and Programming

Output:  222232244629420445529739893461909967206666939096499764990979600

PEP8 Style Compliant:
In Spyder: Preferences -> Editor -> Code Introspection/Analysis,
 near the bottom right, check Style analysis (pep8).


The 2nd way to run it:
 - Comment out "@my_memoize"
 - Uncomment "fib = my_memoize(fib)"
 - Run


The 3rd way to run it:
 >> from fib_mem import fib
 >> print(fib(300))


Tested on Python 3.x
"""


##########################################
# Example 1



def my_memoize(f):
    cache = {}


    def helper(*x):  # Refer to Item 18 of "Effective Python"
        if x not in cache:
            cache[x] = f(*x)
        return cache[x]
    return helper


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

# fib = memoize(fib)
print(fib(300))



##########################################
# Example 2 (stack overflow)
def functionDecorator(f):
    def new_f():
        print("Begin", f.__name__)
        foo() # using f() instead
        print("End", f.__name__)
        return new_f


@functionDecorator
def foo():
    print("inside foo()")


foo()
print(foo.__name__)


###############################################################


"Python is basically pseudo code, ..." -- Brett Slatkin, The author of "Effective Python".


No comments:

Post a Comment