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

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

    Let's not forget the built-in hasattr function, for those who want to hand-craft. That way you can keep the mem cache inside the function definition (as opposed to a global).

    def fact(n):
        if not hasattr(fact, 'mem'):
            fact.mem = {1: 1}
        if not n in fact.mem:
            fact.mem[n] = n * fact(n - 1)
        return fact.mem[n]
    

提交回复
热议问题