使用Python中的字典进行记忆

时间:2015-11-10 11:14:53

标签: 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

它正在返回

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

我理解的是因为我没有返回任何东西所以我怎么能做这样的事情。

return cache[s1, s2] = 1 + lcs(s1[:-1], s2[:-1])

我试图在不使用任何装饰器的情况下实现它。

1 个答案:

答案 0 :(得分:2)

试试这个

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)]