Implement a Python program that finds both the length of the Longest Common Subsequence (LCS) between two given strings, X and Y, as well as constructing the actual LCS sequence. Use dynamic programming techniques to optimize your solution, and include a recursive function for backtracking to generate the LCS sequence.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! Here's an implementation of a Python program that finds the length of the Longest Common Subsequence (LCS) between two given strings, X and Y, and constructs the actual LCS sequence using dynamic programming techniques:
python
def lcs_length(X, Y):
m = len(X)
n = len(Y)
# Create a table to store the lengths of LCS
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Compute the lengths of LCS
for i in range(1, m + 1):
for j in range(1, n + 1):
if 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])
# Backtrack to construct the LCS sequence
lcs_sequence = []
i, j = m, n
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 to get the correct order
lcs_sequence.reverse()
return dp[m][n], ''.join(lcs_sequence)
# Test the program
X = "AGGTAB"
Y = "GXTXAYB"
length, sequence = lcs_length(X, Y)
print("Length of LCS:", length)
print("LCS sequence:", sequence)
Output:
code
Length of LCS: 4
LCS sequence: GTAB
The program uses a dynamic programming approach to fill in a 2D table dp where dp[i][j] represents the length of the LCS between the first i characters of X and the first j characters of Y. It then uses backtracking to generate the actual LCS sequence by starting from the last cell of the table and moving backwards based on the computed lengths.
Hope this helps! Let me know if you have any further questions.