def lcs(X, Y): # 创建一个二维数组 m = len(X) n = len(Y) L = [[None]*(n+1) for i in range(m+1)] # 填充L [i] [0] = 0 和 L [0] [j] = 0 for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 # 填充L [i] [j],如果X [i-1] == Y [j-1],则L [i] [j] = L [i-1] [j-1] +1,否则L [i] [j] = max(L [i-1] [j],L [i] [j-1]) for i in range(1, m+1): for j in range(1, n+1): if X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) # L [m] [n]存储LCS的长度值 return L[m][n代码运行不出来
时间: 2023-10-17 13:05:14 浏览: 99
抱歉,可能是因为代码中存在一些格式错误导致不能正常运行。以下是修改后的代码:
```python
def lcs(X, Y):
# 创建一个二维数组
m = len(X)
n = len(Y)
L = [[None]*(n+1) for i in range(m+1)]
# 填充L [i] [0] = 0 和 L [0] [j] = 0
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0:
L[i][j] = 0
# 填充L [i] [j],如果X [i-1] == Y [j-1],则L [i] [j] = L [i-1] [j-1] +1,否则L [i] [j] = max(L [i-1] [j],L [i] [j-1])
for i in range(1, m+1):
for j in range(1, n+1):
if X[i-1] == Y[j-1]:
L[i][j] = L[i-1][j-1] + 1
else:
L[i][j] = max(L[i-1][j], L[i][j-1])
# L [m] [n]存储LCS的长度值
return L[m][n]
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", lcs(X, Y))
```
这段代码可以计算出 X 和 Y 的最长公共子序列的长度,输出结果为 4。
阅读全文