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

前端 未结 13 1181
情歌与酒
情歌与酒 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:17

    I've found this extremely useful

    def memoize(function):
        from functools import wraps
    
        memo = {}
    
        @wraps(function)
        def wrapper(*args):
            if args in memo:
                return memo[args]
            else:
                rv = function(*args)
                memo[args] = rv
                return rv
        return wrapper
    
    
    @memoize
    def fibonacci(n):
        if n < 2: return n
        return fibonacci(n - 1) + fibonacci(n - 2)
    
    fibonacci(25)
    

提交回复
热议问题