因此,我正在尝试在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)
我试图在不使用任何装饰器的情况下实现它.
所以我有这个字符串.
6#666#665533999
Run Code Online (Sandbox Code Playgroud)
我想把它解析成多个小字符串(或直到字符改变)并忽略它,#
以便我可以6 = M or 666 = O or 9 = W
像电话的拨号盘一样替换它.
6#666#665533999 -> 6, 666, 66, 55, 33, 999
Run Code Online (Sandbox Code Playgroud)
所以我用这个split('#')
方法删除了#
,并且无法弄清楚接下来要做什么.我尝试过一些蛮力方法,它在一定程度上解决了这个问题但是有没有更容易或更优雅的解决方案呢?