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

前端 未结 13 1173
情歌与酒
情歌与酒 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 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.

提交回复
热议问题