0

The term "memoization" was introduced by Donald Michie in the year 1968. This is accomplished by memorizing the calculation results of processed input such as the results of function calls. If the same input or a function call with the same parameters is used, the previously stored results can be used again and unnecessary calculation are avoided.

My function:

def fibonnaci(n):

    if n ==0 or n == 1:
        return 1
    else:

        return fibonnaci(n - 1) + fibonnaci(n - 2), total_call


n =8
print(fibonnaci(n))

I did not understand how to use it in practice. Could anyone explain how to use memoization in fibonacci calculus?

Laurinda Souza
  • 1,207
  • 4
  • 14
  • 29

1 Answers1

2

The easiest way is to use the built-in least-recently-used memoizer (note the fix in the return statement):

from functools import lru_cache                                                                     

@lru_cache()  # will cache 128 most recently used results by default. Use maxsize=.. to change this number
def fibonnaci(n): 
    if n ==0 or n == 1: 
        return 1 
    else:
        return fibonnaci(n - 1) + fibonnaci(n - 2) 

Internally, the memoizer looks something like this:

def lru_cache(maxsize=128):
    cache = {}  # cache[key] = (count, return value)
    def wrapper(func):
        def _func(*args, **kwargs):
            cache_key = '::'.join(args)  # lazy version; don't try this at home
            if cache_key not in cache:
                # delete least recent used value
                key2delete = min(cache.keys(), key=lambda key: cache[key][0])
                del cache[key2delete]
                cache[cache_key] = [0, func(*args, **kwargs)]
            cache[cache_key][0] += 1
            return cache[cache_key][1]
        return _func
    return wrapper

without cache invalidation, it will simplify to:

def memoize(func):
    cache = {}  # cache[key] = value
    def wrapper(*args, **kwargs):
        cache_key = '::'.join(args)  # lazy version; don't try this at home
        if cache_key not in cache:
            cache[cache_key] = func(*args, **kwargs)
        return cache[cache_key]
    return wrapper
Marat
  • 15,215
  • 2
  • 39
  • 48