0

I am trying to find the LCS between two sequences: TACGCTGGTACTGGCAT and AGCTGGTCAGAA. I want my answer to output as a matrix so that I can backtrack which sequence is common (GCTGGT). When I use my code below, I am getting the following error. IndexError: list index out of range. How can I avoid this error in my code below?

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
4

1 回答 1

0

您需要追加到您的列表中,因为该索引[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]]
于 2014-09-28T20:46:41.233 回答