write a program to align 2 strings and print them in 2 lines, where the same characters…
- User
write a program to align 2 strings and print them in 2 lines, where the same characters should be matched as most as possible in the same position (i guess need to use LCS algorithm as helper)
Assistant
Here is a Python program to align two strings and print them in 2 lines using the Longest Common Subsequence (LCS) algorithm:
def lcs(X, Y): m = len(X) n = len(Y) L = [[None]*(n+1) for i in range(m+1)] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0 : L[i][j] = 0 elif 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]) return L[m][n] def align(X, Y): m = len(X) n = len(Y) L = [[0 for x in range(n+1)] for x in range(m+1)] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 elif 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]) index = L[m][n] lcs = [""] * (index+1) lcs[index] = "" i = m j = n while i > 0 and j > 0: if X[i-1] == Y[j-1]: lcs[index-1] = X[i-1] i-=1 j-=1 index-=1 elif L[i-1][j] > L[i][j-1]: i-=1 else: j-=1 print("Aligned strings:") print(X) print(Y) X = "AGGTAB" Y = "GXTXAYB" align(X,Y)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.