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

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

    Memoization is basically saving the results of past operations done with recursive algorithms in order to reduce the need to traverse the recursion tree if the same calculation is required at a later stage.

    see http://scriptbucket.wordpress.com/2012/12/11/introduction-to-memoization/

    Fibonacci Memoization example in Python:

    fibcache = {}
    def fib(num):
        if num in fibcache:
            return fibcache[num]
        else:
            fibcache[num] = num if num < 2 else fib(num-1) + fib(num-2)
            return fibcache[num]
    

提交回复
热议问题