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

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

    Memoization is keeping the results of expensive calculations and returning the cached result rather than continuously recalculating it.

    Here's an example:

    def doSomeExpensiveCalculation(self, input):
        if input not in self.cache:
            
            self.cache[input] = result
        return self.cache[input]
    

    A more complete description can be found in the wikipedia entry on memoization.

提交回复
热议问题