我一直在使用下面的memoizing裝飾器(從偉大的書籍Python算法:在Python語言掌握基本算法...愛它,順便說一句)。Python - 任何人都有一個memoizing裝飾器,可以處理不可參數的參數?
def memo(func):
cache = {}
@ wraps(func)
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
與這個裝飾的問題是,基於字典的緩存意味着我所有的參數都必須是可哈希。
有沒有人有一個實現(或調整到這一個),允許不可干擾的參數(例如字典)?
我知道缺少散列值意味着「這是在緩存中嗎?」的問題。變得不平凡,但我只是想我會問。
===編輯,以給定的上下文===
我上一個返回爾格式功能工作的「使用層次結構」給定模塊的字典:依賴關係。這裏的設置:
def uses_hierarchy(requirements):
"""
uses_hierarchy(requirements)
Arguments:
requirements - a dictionary of the form {mod: list of dependencies, }
Return value:
A dictionary of the form {level: list of mods, ...}
Assumptions:
- No cyclical requirements (e.g. if a requires b, b cannot require a).
- Any dependency not listed as a mod assumed to be level 0.
"""
levels = dict([(mod, _level(mod, requirements))
for mod in requirements.iterkeys()])
reversed = dict([(value, []) for value in levels.itervalues()])
for k, v in levels.iteritems():
reversed[v].append(k)
return reversed
def _level(mod, requirements):
if not requirements.has_key(mod):
return 0
dependencies = requirements[mod]
if not dependencies:
return 0
else:
return max([_level(dependency, requirements)
for dependency in dependencies]) + 1
這樣:
>>> requirements = {'a': [],
... 'b': [],
... 'c': ['a'],
... 'd': ['a','b'],
... 'e': ['c','d'],
... 'f': ['e']
... }
>>> uses_hierarchy(requirements)
{0: ['a', 'b'], 1: ['c', 'd'], 2: ['e'], 3: ['f']}
_level是我想memoize的,使這個設置更具擴展性的功能。如果不使用memoization實現,它會多次計算依賴關係的級別(例如,在上面的示例中,我認爲「a」的計算次數是8次)。
感謝,
邁克
好吧,只需將它們作爲`(args,result)`的元組存儲在一個列表中,然後遍歷它。就像你說的那樣,它不會很快。 – 2011-01-12 13:51:17
@Thomas K:一個緩存越慢,它所擁有的條目越多,確實會起反作用。 – 2011-01-12 13:59:48
@ THC4k:這取決於你想要它。如果你將會多次碰到同樣的可能性,並且這個函數是一個很大的計算,或者是一個緩慢的網絡請求,它可能不夠好。在現代計算機上,它可以在出現問題之前變得相當大。 – 2011-01-12 15:29:27