2015-11-10 30 views
6

所以我試圖實現Python中的最低公共子序列,並試圖將此替代方案用於我以前的解決方案。我嘗試使用字典而不是2-D矩陣來記憶結果。在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

'cache'不能是本地的,你是想memoize的 –

+0

@JohnColeman感謝您指出了這一點的功能。 – Angersmash

回答

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

非常感謝你!我試圖實現這樣的東西,你的解決方案工作。創建用於存儲結果的2-D矩陣更直觀。 – Angersmash

+0

好。將答案標記爲正確答案,以便其他人可以從中獲益。 –