What is memoization and how can I use it in Python?

前端 未结 13 1174
情歌与酒
情歌与酒 2020-11-21 17:25

I just started Python and I\'ve got no idea what memoization is and how to use it. Also, may I have a simplified example?

相关标签:
13条回答
  • 2020-11-21 17:55

    Let's not forget the built-in hasattr function, for those who want to hand-craft. That way you can keep the mem cache inside the function definition (as opposed to a global).

    def fact(n):
        if not hasattr(fact, 'mem'):
            fact.mem = {1: 1}
        if not n in fact.mem:
            fact.mem[n] = n * fact(n - 1)
        return fact.mem[n]
    
    0 讨论(0)
  • 2020-11-21 17:56
    cache = {}
    def fib(n):
        if n <= 1:
            return n
        else:
            if n not in cache:
                cache[n] = fib(n-1) + fib(n-2)
            return cache[n]
    
    0 讨论(0)
  • 2020-11-21 18:02

    New to Python 3.2 is functools.lru_cache. By default, it only caches the 128 most recently used calls, but you can set the maxsize to None to indicate that the cache should never expire:

    import functools
    
    @functools.lru_cache(maxsize=None)
    def fib(num):
        if num < 2:
            return num
        else:
            return fib(num-1) + fib(num-2)
    

    This function by itself is very slow, try fib(36) and you will have to wait about ten seconds.

    Adding lru_cache annotation ensures that if the function has been called recently for a particular value, it will not recompute that value, but use a cached previous result. In this case, it leads to a tremendous speed improvement, while the code is not cluttered with the details of caching.

    0 讨论(0)
  • 2020-11-21 18:08

    Memoization is the conversion of functions into data structures. Usually one wants the conversion to occur incrementally and lazily (on demand of a given domain element--or "key"). In lazy functional languages, this lazy conversion can happen automatically, and thus memoization can be implemented without (explicit) side-effects.

    0 讨论(0)
  • 2020-11-21 18:10

    The other answers cover what it is quite well. I'm not repeating that. Just some points that might be useful to you.

    Usually, memoisation is an operation you can apply on any function that computes something (expensive) and returns a value. Because of this, it's often implemented as a decorator. The implementation is straightforward and it would be something like this

    memoised_function = memoise(actual_function)
    

    or expressed as a decorator

    @memoise
    def actual_function(arg1, arg2):
       #body
    
    0 讨论(0)
  • 2020-11-21 18:12

    Memoization is keeping the results of expensive calculations and returning the cached result rather than continuously recalculating it.

    Here's an example:

    def doSomeExpensiveCalculation(self, input):
        if input not in self.cache:
            <do expensive calculation>
            self.cache[input] = result
        return self.cache[input]
    

    A more complete description can be found in the wikipedia entry on memoization.

    0 讨论(0)
提交回复
热议问题