Ang*_*ash 6 python memoization
因此,我正在尝试在Python中实现最低公共子序列,并尝试使用此先前解决方案的替代方案.我尝试使用字典而不是二维矩阵来记忆结果.
def lcs(s1, s2):
cache = {}
if len(s1) == 0 or len(s2) == 0:
return 0
if (s1, s2) in cache:
return cache[s1, s2]
else:
if s1[-1] == s2[-1]:
cache[s1, s2] = 1 + lcs(s1[:-1], s2[:-1])
else:
cache[s1, s2] = max(lcs(s1[:-1], s2), lcs(s1, s2[:-1]))
print cache
Run Code Online (Sandbox Code Playgroud)
它正在回归
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Run Code Online (Sandbox Code Playgroud)
我理解的是因为我没有返回任何东西,所以我怎么能做这样的事情.
return cache[s1, s2] = 1 + lcs(s1[:-1], s2[:-1])
Run Code Online (Sandbox Code Playgroud)
我试图在不使用任何装饰器的情况下实现它.
尝试这个
cache = {}
def lcs(s1, s2):
global cache
if len(s1) == 0 or len(s2) == 0:
return 0
if (s1, s2) in cache:
return cache[(s1, s2)]
else:
if s1[-1] == s2[-1]:
cache[(s1, s2)] = 1 + lcs(s1[:-1], s2[:-1])
else:
cache[(s1, s2)] = max(lcs(s1[:-1], s2), lcs(s1, s2[:-1]))
return cache[(s1, s2)]
Run Code Online (Sandbox Code Playgroud)