How to find the longest common substring from more than two strings in Python?


In this article, we are going to find the longest common substring from more than two strings in Python.

The first and only approach for finding the longest common substring is by using the Longest common substring Algorithm. We will define a function that accepts 2 strings, then we will iterate over both the strings and find for common subsequence and calculate the length.

We will check entire string by iterating over and calculating the length of the sub-sequences and we will return the longest common subsequence. We will get an empty string as output if there are not any common sub-sequences between two given strings.

Example

In the example given below, we are taking 2 strings as input and we are showing the implementation of the Longest Common Subsequence Algorithm and finding the Longest Common Subsequence 

def longest_common_substring(str1, sub):
   m = [[0] * (1 + len(sub)) for i in range(1 + len(str1))]
   longest, x_longest = 0, 0
   for x in range(1, 1 + len(str1)):
      for y in range(1, 1 + len(sub)):
         if str1[x - 1] == sub[y - 1]:
            m[x][y] = m[x - 1][y - 1] + 1
            if m[x][y] > longest:
               longest = m[x][y]
               x_longest = x
            else:
               m[x][y] = 0
   return str1[x_longest - longest: x_longest]
   
str1 = "Welcome to Tutorialspoint"
print("The given string is ")
print(str1)

sub1 = "Tutorial"
print("The first sub-string is")
print(sub1)
print("The longest common subsequence between'",str1,"'and '",sub1,"' is")
print(longest_common_substring(str1, sub1))

sub2 = "12345"
print("The second sub-string is")
print(sub2)
print("The longest common subsequence between'",str1,"'and '",sub2,"' is")
print(longest_common_substring(str1, sub2))

Output

Following is an output of the above code −

The given string is
Welcome to Tutorialspoint
The first sub-string is
Tutorial
The longest common subsequence between' Welcome to Tutorialspoint 'and ' Tutorial ' is Tutorial
1
The second sub-string is
12345
The longest common subsequence between' Welcome to Tutorialspoint 'and ' 12345 ' is

Updated on: 07-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements