# L-10 MCS 275 Wed 3 Feb 2010 : memofib.py # Memoization is a optimization technique to speedup programs by # storing results of previous function calls. # We illustrate how to memoize a recursive function to compute # Fibonacci numbers using a dictionary. from sys import setrecursionlimit class MemoizedFibonacci(): """ The class exports a data attribute D that stores the results of all calls made to the functional attribute F. """ def __init__(self): """ Initializes the dictionary. """ self.D = {} def F(self,n): """ returns the n-th Fibonacci number """ if self.D.has_key(n): return self.D[n] else: if n == 0: R = 0 elif n == 1: R = 1 else: R = self.F(n-1) + self.F(n-2) self.D[n] = R return R def main(): """ Prompts the user for a number n, instantiates an object m of the class MemoizedFibonacci and applies the method F to the object m and shows m.D. """ m = MemoizedFibonacci() n = input('Give a number : ') setrecursionlimit(n+2) f = m.F(n) print 'The %d-th Fibonacci number is %d' % (n,f) print 'The dictionary of function calls :' print m.D if __name__=="__main__": main()