【Python】python 中 的 memoize 和 memoized

【Python】python 中 的 memoize 和 memoized,第1张

概述python中编写递归函数时,为减少计算时间,需要用到memoize或memoized功能。它们的作用是:记忆函数每次运行的结果,当递归函数每次递归时,若已经计算过子函数,就直接从记忆中的结果获取,避免重复计算。

python 中编写递归函数时,为减少计算时间,需要用到 memoize 或 memoized 功能。

它们的作用是:记忆函数每次运行的结果,当递归函数每次递归时,若已经计算过子函数,就直接从记忆中的结果获取,避免重复计算。

在使用这个功能时,一般在程序前面加个 memoized 的类(这个类可以直接复制别人写好的代码)就行,然后在定义递归函数时前面加上 @memoized

例如斐波那契函数,没有使用 memoized 功能的计算时间为 41 秒,使用后计算时间为 0秒。href="https://blog.csdn.net/robert_chen1988/article/details/80534915?utm_source=copy" rel="nofollow">点击此处看原文斐波那契数列的代码。

memoized 类的代码(decorator.py):

<pre >
import collections
import functools

class memoized(object):
"""Decorator. Caches a function's return value each time it is called.
If called later with the same arguments,the cached value is returned
(not reevaluated).
"""
def init(self,func):
self.func = func
self.cache = {}

def __call__(self,*args):    if not <a href="https://www.jb51.cc/tag/isinstance/" target="_blank" >isinstance</a>(args,c<a href="https://m.jb51.cc/tag/ol/" target="_blank" >ol</a>lections.Hashable):        # uncacheable. a <a href="https://m.jb51.cc/tag/List/" target="_blank" >List</a>,for instance.        # better to not cache than blow up.        return self.func(*args)    if args in self.cache:        return self.cache[args]    else:        value = self.func(*args)        self.cache[args] = value        return valuedef __repr__(self):    """Return the function's docstring."""    return self.func.__doc__def <a href="https://www.jb51.cc/tag/get/" target="_blank" >__get__</a>(self,obj,objtype):    """Support instance methods."""    return <a href="https://www.jb51.cc/tag/functools/" target="_blank" >functools</a>.partial(self.__call__,obj)</code></pre>

使用:

<pre >
#Coding: utf-8
from decorators import memoized
def myclass(object):
@memoized
def init(a,b):
return a+b

总结

以上是内存溢出为你收集整理的【Python】python 中 的 memoize 和 memoized全部内容,希望文章能够帮你解决【Python】python 中 的 memoize 和 memoized所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1209104.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-04
下一篇2022-06-04

发表评论

登录后才能评论

评论列表(0条)