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

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

提交回复
热议问题