簡體   English   中英

最長公共序列-索引錯誤

[英]Longest Common Sequence -Index Error

我試圖在兩個序列之間找到LCS:TACGCTGGTACTGGCAT和AGCTGGTCAGAA。 我希望我的答案以矩陣形式輸出,以便可以回溯常見的序列(GCTGGT)。 當我在下面使用我的代碼時,出現以下錯誤。 IndexError:列表索引超出范圍。 如何在下面的代碼中避免該錯誤?

def LCS(x, y):
    m = len(x)
    n = len(y)
    C = []  
    for i in range(m):
        for j in range(n):
            if x[i] == y[j]:
                C[i][j] == C[i-1][j-1] + 1
            else:
                C[i][j] == 0
    return C


x = "TACGCTGGTACTGGCAT"
y = "AGCTGGTCAGAA"
m = len(x)
n = len(y)
C = LCS(x, y)

print C

您需要追加到列表中,因為索引[i][j]尚不存在。

def LCS(x, y):
    m = len(x)
    n = len(y)
    C = []  
    for i in range(m):
    C.append([])          # append a blank list at index [i]
        for j in range(n):
            if x[i] == y[j]:
                C[i].append(C[i-1][j-1] + 1)   # append current element to [i]
            else:
                C[i].append(0)
    return C

測試中

x = "TACGCTGGTACTGGCAT"
y = "AGCTGGTCAGAA"
LCS(x,y)

輸出量

[[0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
 [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1],
 [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
 [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0],
 [0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0],
 [0, 0, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0],
 [0, 1, 0, 0, 4, 1, 0, 0, 0, 1, 0, 0],
 [0, 1, 0, 0, 1, 5, 0, 0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0, 0, 6, 0, 0, 0, 0, 0],
 [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1],
 [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
 [0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0],
 [0, 1, 0, 0, 3, 1, 0, 0, 0, 1, 0, 0],
 [0, 1, 0, 0, 1, 4, 0, 0, 0, 1, 0, 0],
 [0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 1],
 [0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM