def LCS(A,B): n = len(A) m = len(B) A.insert(0,'0') B.insert(0,'0') c = [([0]*(m+1)) for i in range(n+1)] b = [([0]*(m+1)) for i in range(n+1)] for i in range(0,n+1): for j in range(0,m+1): if (i==0 or j==0): c[i][j] = 0 elif A[i] == B[j]: c[i][j] = (c[i-1][j-1] + 1) b[i][j] = 0 elif c[i-1][j] >= c[i][j-1]: c[i][j] = c[i-1][j] b[i][j] = 1 else: c[i][j] = c[i][j-1] b[i][j] = -1 return c,b def printLCS(s,A,i,j): global res if (i==0 or j==0): return 0 if s[i][j] == 0: printLCS(s,A,i-1,j-1) res.append(A[i]) elif s[i][j] == 1: printLCS(s,A,i-1,j) else: printLCS(s,A,i,j-1) if __name__ == "__main__": A = ['z','x','y','x','y','z'] B = ['x','y','y','z','x'] res = [] n = len(A) m = len(B) c,s = LCS(A,B) printLCS(s,A,n.m) print(res)修改这段代码
时间: 2024-03-01 16:49:31 浏览: 66
这段代码是一个实现最长公共子序列(LCS)的算法,其中LCS函数实现了动态规划算法,返回了LCS矩阵c和b,printLCS函数则利用LCS矩阵s和输入的序列A输出最长公共子序列。在修改代码时,需要修正两处错误:1. printLCS函数调用时,逗号应该改为点号;2. 在printLCS函数中,第二个参数应为n和m,而不是n.m,应该修改为printLCS(s,A,n,m)。另外,res列表需要在printLCS函数之前定义。
相关问题
def LCS(A,B): n = len(A) m = len(B) A.insert(0,'0') B.insert(0,'0') c = [([0]*(m+1)) for i in range(n+1)] b = [([0]*(m+1)) for i in range(n+1)] for i in range(0,n+1): for j in range(0,m+1): if (i==0 or j==0)
: c[i][j]=0 elif A[i]==B[j]: c[i][j]=c[i-1][j-1]+1 b[i][j]='↖' elif c[i-1][j]>=c[i][j-1]: c[i][j]=c[i-1][j] b[i][j]='↑' else: c[i][j]=c[i][j-1] b[i][j]='←' return c,b
这段代码实现了什么功能?
阅读全文