0

我试图找到两个 DNA 序列的 LCS。我正在输出矩阵形式以及包含最长公共序列的字符串。但是,当我在代码中同时返回矩阵和列表时,我收到以下错误:IndexError: string index out of range

如果我要删除涉及变量 temp 和 higestcount 的编码,我的代码将很好地输出我的矩阵。我正在尝试对矩阵使用类似的编码来生成我的列表。有没有办法避免这个错误?根据序列 AGCTGGTCAG 和 TACGCTGGTGGCAT,最长的公共序列应该是 GCTGGT。

def lcs(x,y):
    c = len(x)
    d = len(y)
    plot = []
    temp = ''
    highestcount = ''

    for i in range(c):
        plot.append([])
        temp.join('')
        for j in range(d):
            if x[i] == y[j]:
                plot[i].append(plot[i-1][j-1] + 1)
                temp.join(temp[i-1][j-1])
            else:
                plot[i].append(0)
                temp = ''
                if temp > highestcount:
                    highestcount = temp

    return plot, temp

x = "AGCTGGTCAG"
y = "TACGCTGGTGGCAT"
test = compute_lcs(x,y)

print test
4

3 回答 3

0

temp.join(temp[i-1][j-1])temp 作为变量的第一次迭代中是一个空字符串,''

字符串中没有可以被索引调用的字符,因此 temp[any_number] 会抛出index out of range异常。

于 2014-09-29T01:19:16.707 回答
0

据我所知, join() 通过另一个字符串连接一个字符串数组。例如,"-".join(["a", "b", "c"])将返回a-b-c.

此外,您从定义temp为字符串开始,但稍后使用双索引引用它,几乎就像它是一个数组一样。据我所知,您可以通过单个索引调用来引用字符串中的字符。例如a = "foobar"a[3]返回b

我将您的代码更改为以下内容。初始化数组以开始以避免索引问题。

def lcs(x,y):
    c = len(x)
    d = len(y)
    plot = [[0 for j in range(d+1)] for i in range(c+1)]
    temp = [['' for j in range(d+1)] for i in range(c+1)]
    highestcount = 0
    longestWord = ''

    for i in range(c):
        for j in range(d):
            if x[i] == y[j]:
                plot[i+1][j+1] = plot[i][j] + 1
                temp[i+1][j+1] = ''.join([temp[i][j],x[i]])
            else:
                plot[i+1][j+1] = 0
                temp[i+1][j+1] = ''
                if plot[i][j] > highestcount:
                    highestcount = plot[i][j]
                    longestWord = temp[i][j]

    return plot, temp, highestcount, longestWord

x = "AGCTGGTCAG"
y = "TACGCTGGTGGCAT"
test = lcs(x,y)
print test
于 2014-09-29T01:46:04.320 回答
0

在我看来,您正在浏览一个不必要的复杂屏幕,这会导致混乱,包括其他人提到的空字符串。

例如,这仍然很冗长,但我认为更容易理解(并返回预期的答案):

def lcs(seq1, seq2):
    matches = []
    for i in range(len(seq1)):
        j = 1
        while seq1[i:j] in seq2:
            j+=1 
            if j > len(seq1):
                break
        matches.append( (len(seq1[i:j-1]), seq1[i:j-1]) )
    return max(matches)

seq1 = 'AGCTGGTCAG'
seq2 = 'TACGCTGGTGGCAT'
lcs(seq1, seq2)

返回

(6, 'GCTGGT')
于 2014-09-29T02:08:12.880 回答