0

I am doing an exercise to find the longest common subsequence (LSC) without dynamic programming, so far I have the code that returns the longest common subsequence but I also need to return the length of the sequence, what do I have to do?

this is the code that returns the longest common subsequence

def lcs(str1, str2):
    
    if len(str1) == 0 or len(str2) == 0:
        return ""
    if str1[-1] == str2[-1]:
        return lcs(str1[:-1], str2[:-1]) + str1[-1]
  
    t1 = lcs(str1[:-1], str2)
    t2 = lcs(str1, str2[:-1])
    if len(t1) > len(t2):
        return t1
    else:
        return t2


How do I return the length of the sequence?

sinNombre
  • 49
  • 4
  • 3
    What is the difference between your question and "how do I get the length of a sequence"? If this is your code then you must already know how to get the length of a sequence, because you did this multiple times in the code. So what is the problem? – kaya3 Jul 10 '21 at 20:36
  • As it so happens, there's a handy built-in function for that: [`len()`](https://docs.python.org/3/library/functions.html#len). And it appears you're already using it. What, exactly, is your question? – MattDMo Jul 10 '21 at 20:39
  • if the strings are "ABC" and "ACB", the result of the code is "AD", where do I incorporate the len function so that it returns the length, which is two in this case? – sinNombre Jul 10 '21 at 20:42
  • You call the function which returns a string, and then you get the length of the string by calling `len` on it. – kaya3 Jul 10 '21 at 20:42
  • I need the above code to return the size – sinNombre Jul 10 '21 at 20:47

1 Answers1

0

Just have your return statements return the length of the string that would have been returned in the original:

def lcs(str1, str2):
    if len(str1) == 0 or len(str2) == 0:
        return 0 #len("")
    if str1[-1] == str2[-1]:
        return lcs(str1[:-1], str2[:-1]) + 1
    return max(lcs(str1[:-1], str2),lcs(str1, str2[:-1]))
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101