最长公共序列语法

2024-10-02 08:30:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图找到两个DNA序列的LCS。我将输出矩阵形式以及包含最长公共序列的字符串。但是,当我在代码中同时返回矩阵和列表时,会出现以下错误:IndexError:字符串索引超出范围

如果我删除包含变量temp和higestcount的代码,我的代码将很好地输出我的矩阵。我正在尝试对矩阵使用类似的编码来生成我的列表。有没有办法避免这个错误?根据序列AGCTGGCAG和TACGCTGGCAT,最长的公共序列应该是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

Tags: 字符串代码in列表forlenplot错误
3条回答

据我所知,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

在我看来,您正在经历一个不必要的复杂屏幕,这导致了混乱,包括其他人提到的空字符串。你知道吗

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

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')

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

字符串中没有可由索引调用的字符,因此temp[任何\u数字]将抛出index out of range异常。你知道吗

相关问题 更多 >

    热门问题