Python:构造和打印矩阵

Python: Constructing & Printing matrices

我需要创建一个矩阵来计算 LCS,然后将其打印出来。这是我的代码,但我在使用打印功能时遇到了问题(不知道如何将 LCSmatrix 值输入到打印中)

def compute_LCS(seqA, seqB):

    for row in seqA:
    for col in seqB:
        if seqA[row] == seqB[col]:
            if row==0 or col==0:
                LCSmatrix(row,col) = 1
            else:
                LCSmatrix(row,col) = LCS(row-1,col-1) + 1 
        else: 
            LCSmatrix(row,col) = 0
return LCSmatrix


def printMatrix(parameters...):
    print ' ',
    for i in seqA:
          print i,
    print
    for i, element in enumerate(LCSMatrix):
          print i, ' '.join(element)

matrix = LCSmatrix


print printMatrix(compute_LCS(seqA,seqB))

如有任何帮助,我们将不胜感激。

试试这个:

seqA='AACTGGCAG'
seqB='TACGCTGGA'

def compute_LCS(seqA, seqB):
    LCSmatrix = [len(seqB)*[0] for row in seqA]
    for row in range(len(seqB)):
        for col in range(len(seqA)):
            if seqB[row] == seqA[col]:
                if row==0 or col==0:
                    LCSmatrix[row][col] = 1
                else:
                    LCSmatrix[row][col] = LCSmatrix[row-1][col-1] + 1_
            else:
                LCSmatrix[row][col] = 0
    return LCSmatrix

def printMatrix(seqA, seqB, LCSmatrix):
    print ' '.join('%2s' % x for x in ' '+seqA)
    for i, element in enumerate(LCSmatrix):
        print '%2s' % seqB[i], ' '.join('%2i' % x for x in element)

matrix = compute_LCS(seqA, seqB)
printMatrix(seqA, seqB, matrix)

以上产生:

    A  A  C  T  G  G  C  A  G
 T  0  0  0  1  0  0  0  0  0
 A  1  1  0  0  0  0  0  1  0
 C  0  0  2  0  0  0  1  0  0
 G  0  0  0  0  1  1  0  0  1
 C  0  0  1  0  0  0  2  0  0
 T  0  0  0  2  0  0  0  0  0
 G  0  0  0  0  3  1  0  0  1
 G  0  0  0  0  1  4  0  0  1
 A  1  1  0  0  0  0  0  1  0