python中factorial什么意思,什么是备忘录,如何在Python中使用备忘录?

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?

解决方案

Memoization effectively refers to remembering ("memoization" → "memorandum" → to be remembered) results of method calls based on the method inputs and then returning the remembered result rather than computing the result again. You can think of it as a cache for method results. For further details, see page 387 for the definition in Introduction To Algorithms (3e), Cormen et al.

A simple example for computing factorials using memoization in Python would be something like this:

factorial_memo = {}

def factorial(k):

if k < 2: return 1

if k not in factorial_memo:

factorial_memo[k] = k * factorial(k-1)

return factorial_memo[k]

You can get more complicated and encapsulate the memoization process into a class:

class Memoize:

def __init__(self, f):

self.f = f

self.memo = {}

def __call__(self, *args):

if not args in self.memo:

self.memo[args] = self.f(*args)

#Warning: You may wish to do a deepcopy here if returning objects

return self.memo[args]

Then:

def factorial(k):

if k < 2: return 1

return k * factorial(k - 1)

factorial = Memoize(factorial)

A feature known as "decorators" was added in Python 2.4 which allow you to now simply write the following to accomplish the same thing:

@Memoize

def factorial(k):

if k < 2: return 1

return k * factorial(k - 1)

The Python Decorator Library has a similar decorator called memoized that is slightly more robust than the Memoize class shown here.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值