📜 ⬆️ ⬇️

Python Memoization

Memoization is the property of functions to save (cache) the results of calculations in order not to calculate later on again.

This optimization technology will allow to increase the speed of work due to losses in free memory.

Suppose we have a certain function bigfunc, the result of which depends only on the arguments passed to it, and the computational complexity is quite large. Naturally, we would not want to make calculations on every call of bigfunc if it has already been called before with the same parameters. This is where memoization comes to our rescue.
')
For python, the decorator for the function will look like this:

 import cPickle
 def memoized (func):
     memory = {}
     def memo (* args, ** kwargs):
        hash = cPickle.dumps ((args, sorted (kwargs.iteritems ())))
        if hash not in memory:
            memory [hash] = func (* args, ** kwargs)
        return memory [hash]
     return memo

Further, it is enough for us to declare bigfunc as

  @memoized
 def bigfunc (...):
 ... 

Or override if it is already declared:

  bigfunc = memoized (bigfunc) 

The decorator, declared at the beginning of the article, works only with pickled objects. If your function works with non-pickled objects, you can replace

  hash = cPickle.dumps ((args, sorted (kwargs.iteritems ()))) 

on

  hash = (tuple (args), frozenset (kwargs.items ()) 

but you lose the ability to work with mutable objects.

The decorator can be easily modified to limit the number of cached elements.

Source: https://habr.com/ru/post/50477/


All Articles