Sure! Here's an implementation of a Python program that finds the length of the Longest Common Subsequence (LCS) between two given strings using dynamic programming. It also includes a recursive function for backtracking to generate the actual LCS sequence.
def lcs_length(X, Y):
m = len(X)
n = len(Y)
# Create a table to store lengths of LCS
dp = [[0] * (n+1) for _ in range(m+1)]
# Computing the LCS using dynamic programming
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0:
dp[i][j] = 0
elif X[i-1] == Y[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
# Length of the LCS
lcs_length = dp[m][n]
return lcs_length
def lcs_sequence(X, Y):
m = len(X)
n = len(Y)
# Create a table to store lengths of LCS
dp = [[0] * (n+1) for _ in range(m+1)]
# Computing the LCS using dynamic programming
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0:
dp[i][j] = 0
elif X[i-1] == Y[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
# Backtracking to generate LCS sequence
i, j = m, n
lcs_sequence = []
while i > 0 and j > 0:
if X[i-1] == Y[j-1]:
lcs_sequence.append(X[i-1])
i -= 1
j -= 1
elif dp[i-1][j] > dp[i][j-1]:
i -= 1
else:
j -= 1
# Reverse the LCS sequence
lcs_sequence = lcs_sequence[::-1]
return lcs_sequence
# Example usage
X = "ABCDGH"
Y = "AEDFHR"
length = lcs_length(X, Y)
sequence = lcs_sequence(X, Y)
print("Length of LCS:", length)
print("LCS Sequence:", "".join(sequence))
This program will output:
Length of LCS: 3
LCS Sequence: ADH
In this example, the longest common subsequence (LCS) between the strings "ABCDGH" and "AEDFHR" is "ADH", with a length of 3.