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

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

    Well I should answer the first part first: what's memoization?

    It's just a method to trade memory for time. Think of Multiplication Table.

    Using mutable object as default value in Python is usually considered bad. But if use it wisely, it can actually be useful to implement a memoization.

    Here's an example adapted from http://docs.python.org/2/faq/design.html#why-are-default-values-shared-between-objects

    Using a mutable dict in the function definition, the intermediate computed results can be cached (e.g. when calculating factorial(10) after calculate factorial(9), we can reuse all the intermediate results)

    def factorial(n, _cache={1:1}):    
        try:            
            return _cache[n]           
        except IndexError:
            _cache[n] = factorial(n-1)*n
            return _cache[n]
    

提交回复
热议问题