Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0613· OpenAIHugging Face Arena Human Preference 55K

write a program to align 2 strings and print them in 2 lines, where the same characters…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-2.1’s answer.
  1. 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)

  2. Assistant

    Sure, it seems like you want a program in Python to align two strings by using the Longest Common Subsequence (LCS) algorithm. Here is a simple program that will help you achieve this:

    def lcs(X , Y):
        m = len(X)
        n = len(Y)
        L = [[0]*(n+1) for _ 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
        return "".join(lcs)
    
    def align_strings(X,Y):
        lcs_string = lcs(X,Y)
        align_X = ""
        align_Y = ""
        i = 0
        j = 0
        for k in range(len(lcs_string)):
            while X[i] != lcs_string[k]:
                align_X += X[i]
                align_Y += " "
                i += 1
            while Y[j] != lcs_string[k]:
                align_Y += Y[j]
                align_X += " "
                j += 1
            align_X += X[i]
            align_Y += Y[j]
            i += 1
            j += 1
        print(align_X)
        print(align_Y)
    
    align_strings('abcdef', 'aczdef')
    

    In this program, we first find the Longest Common Subsequence (LCS) of the two input strings. After finding the LCS, we align the two input strings based on the LCS. We insert spaces in string X and string Y wherever there

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.