相关疑难解决方法(0)

什么是memoization以及如何在Python中使用它?

我刚开始使用Python,我不知道什么是memoization以及如何使用它.另外,我可以有一个简化的例子吗?

python memoization

356
推荐指数
9
解决办法
14万
查看次数

我可以记住Python生成器吗?

我有一个runquery调用函数,它调用数据库,然后逐个产生行.我写了一个memoize装饰器(或者更确切地说,我只是从这个stackoverflow问题中偷走了一个)但是在后续调用中它只产生一个空序列,大概是因为生成器的值只能产生一次.

我怎么能修改适用于Python生成器的memoization装饰器?我意识到我需要在某些时候将它存储在内存中,但我想在装饰器中处理它而不是修改原始函数.

memoization函数的当前代码是:

def memoized(f):
    # Warning: Doesn't work if f yields values
    cache={}
    def ret(*args):
        if args in cache:
            return cache[args]
        else:
            answer=f(*args)
            cache[args]=answer
            return answer
    return ret
Run Code Online (Sandbox Code Playgroud)

python generator memoization

22
推荐指数
2
解决办法
3384
查看次数

在内部函数内部分配外部变量的python闭包

我有这段代码:

#!/usr/bin/env python

def get_match():
  cache=[]
  def match(v):
    if cache:
      return cache
    cache=[v]
    return cache
  return match
m = get_match()
m(1)
Run Code Online (Sandbox Code Playgroud)

如果我运行它,它说:

UnboundLocalError: local variable 'cache' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

#!/usr/bin/env python

def get():
  y = 1
  def m(v):
    return y + v
  return m

a=get()
a(1)
Run Code Online (Sandbox Code Playgroud)

它运行.

列表中有什么东西吗?或者我的代码组织错了?

python closures scope python-2.x

15
推荐指数
2
解决办法
3845
查看次数

标签 统计

python ×3

memoization ×2

closures ×1

generator ×1

python-2.x ×1

scope ×1