0

I have two strings

str1 = "bqdrcvefgh"

str2 = "abcvdefgh"

I want to find the LCS between the two strings.But I am encountering string index out of range exception.This is my code

str1 = "bqdrcvefgh"
str2 = "abcvdefgh"
#taking str1 as column and str2 as row
lis = [[0]*(len(str1)+1) for i in range(len(str2)+1)]

#The first row and first column has default value of 0
for i in range(1,len(str2)+1):
    for j in range(1,len(str1)+1):
        if str2[i]==str1[j]:
            lis[i][j] = lis[i-1][j-1]+1
        else:
            lis[i][j] = max(lis[i][j-1],lis[i-1][j])

#length of the longest LCS
print(lis[len(str2)][len(str1)])

What am I doing wrong?

PS-The correct answer is 7

Souvik Ray
  • 2,899
  • 5
  • 38
  • 70

1 Answers1

0

Indexes are running from zero till len-1 (it was running from 1 till len inclusive).

Here's the fixed code:

def lcs(str1, str2):    
    #taking str1 as column and str2 as row
    lis = [[0]*(len(str1)) for i in range(len(str2))]
    for i in range(len(str2)):
        for j in range(len(str1)):
            if str2[i]==str1[j]:
                lis[i][j] = lis[i-1][j-1]+1
            else:
                lis[i][j] = max(lis[i][j-1],lis[i-1][j])

    #length of the longest LCS
    print(lis[len(str2)-1][len(str1)-1])

str1 = "bqdrcvefgh"
str2 = "abcvdefgh"    
lcs(str1, str2)  # prints 7
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129