Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

Problem with Longest Common Substring code

New Here ,
Apr 19, 2023 Apr 19, 2023


Hello,

I'm having an issue with the code from the blog post online about finding the longest common substring. I'm trying to get this code to work, but I'm running into an error.

Here's the code I'm using:

def longestCommonSubstring(str1, str2):
n1 = len(str1)
n2 = len(str2)
table = [[0 for _ in range(n2+1)] for _ in range(n1+1)]
ans = 0
for i in range(1, n1 + 1):
for j in range(1, n2 + 1):
if (str1[i-1] == str2[j-1]):
table[i][j] = table[i-1][j-1] + 1
if (table[i][j] > ans):
ans = table[i][j]
else:
table[i][j] = 0
return ans

str1 = "ABCDGH"
str2 = "ACDGHR"
print(longestCommonSubstring(str1, str2))

When I run the code, I get the following error:

IndexError: string index out of range

Any help would be appreciated. Thank you!

TOPICS
Learning program
170
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Adobe Employee ,
Apr 19, 2023 Apr 19, 2023
LATEST

Hi @ashnaaa29387719lom8,

 

Thank you for contacting Adobe Learning Manager Team.

May I know which Adobe Product you use? We will try our best to help you once we know which product you use.

 

Hope to hear from you soon.

 

Regards,
Debiprasad Maharana
Adobe Inc.

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Resources
Help resources