0

I am suppose to implement a version of LCS that does the following I/O:

input: superLCS('cat','car')

output: ['ca#','ca#']

currently, my program works for that, but if the letters are out of place, it doesnt work.

for example, if the input is: superLCS('art','cad'), it outputs, ['###','###']. It should be outputting ['a##','#a#']

code:

def superLCS(s1,s2):
    return helper(s1,s2,'','')

def helper(s1,s2,res1,res2):  #s1 is string 1, s2 is string 2, res1 is result1, res2 is result2
    if s1 == '' or s2 == '': #if either string is empty return the result
        return [res1,res2]
    if s1[0] == s2[0]: #if they are equal, put their string in the list
        res1 += s1[0]
        res2 += s1[0]
        return helper(s1[1:],s2[1:],res1,res2)
    else:  #if they arent, add a # to the list
        res2 += '#'
        res1 += '#'
        return helper(s1[1:],s2[1:],res1,res2)
user1681664
  • 1,771
  • 8
  • 28
  • 53

1 Answers1

0

Your problem is algorithmic. LCS is a classic dynamic programming algorithm, where you have to fill a "matrix" of dimension len(s1) x len(s2), each value M[i,j] depending on the value of the cell above it M[i-1,j], to its left M[i,j-1], and to the one diagonally above it to the left M[i-1][j-1], and this is just to get the length of the LCS. To retrieve (one of the potential) LCSes, you then need to do an additional "traceback" from the bottom right corner to the upper left.

As you're not doing this, you're doing a simpler, narrower search through the space of subsequences, and thus in your second example the correct LCS is not found.

This is all explained and demonstrated rather nicely on Wikipedia.

Harel
  • 327
  • 1
  • 5