[英]longest common subsequence (restoring sequence)
我有2個序列,需要找到最長的公共子序列。 想不通為什么我的功能恢復不起作用。
#sequenses
A=[1,2,3]
B=[2,3,1,5]
#table AxB
rows=[0]*(len(B)+1)
table=[rows for l in range(len(A)+1)]
for i in range(len(A)):
for k in range(len(B)):
if A[i]==B[k]:
table[i+1][k+1]=table[i][k]+1
else:
table[i+1][k+1]=max(table[i][k+1], table[i+1][k])
print(table)
lst=[]#subsequence
#function to restore subsequence by walking through table
def restore(s1,s2):#s1=len(A)-1, s2=len(B)-1
if s1==-1 or s2==-1:
pass
elif A[s1]==B[s2]:
print (1)
lst.append(A[s1])
restore(s1-1, s2-1)
else:
if table[s1][s2+1]==table[s1+1][s2+1]:
restore(s1-1,s2)
else:
restore(s1, s2-1)
return lst
如果我做
print (restore(2,3))
函數返回
[]
我認為,該問題出在索引中,但找不到它在哪里。
這是您的第一個問題:
rows=[0]*(len(B)+1)
table=[rows for l in range(len(A)+1)]
Python將引用用於列表。 因此,當您創建一堆rows
,實際上是對同一rows
列表的多個引用。 看一下這個測試代碼:
>>> rows = [0]*5
>>> table = [rows for l in range(5)]
>>> table
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> table[0][2] = 4
>>> table
[[0, 0, 4, 0, 0], [0, 0, 4, 0, 0], [0, 0, 4, 0, 0], [0, 0, 4, 0, 0], [0, 0, 4, 0, 0]]
看到單個更改是如何重復的? 那是因為我有5個對同一列表的引用,而不是5個列表。 嘗試這個:
table = [None]*(len(A)+1)
for i in range(len(table)):
table[i] = [0]*(len(B)+1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.