SequenceMatcher in Python for Longest Common Substring.

PythonProgrammingServer Side Programming

Given two strings, our task is to print the longest common sub-string. We will solve problem in python using SequenceMatcher.find_longest_match () method.

Class difflib.SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable.

find_longest_match(a, x, b, y)

Find longest matching block in a[a:x] and b[b:y].

Examples

Input:  str1 = "pythonprogramming", 
        str2 = "pro"
Output: pro

Algorithm

Step 1: Enter two string.
Step 2: initialize SequenceMatcher object with the input string.
Step 3: find the match of longest sub-string output.
Step 4: print longest substring.

Example Code

# Python program to find Longest Common Sub-string 
from difflib import SequenceMatcher 
def matchsubstring(m,n): 
   seqMatch = SequenceMatcher(None,m,n) 
   match = seqMatch.find_longest_match(0, len(m), 0, len(n)) 
   if (match.size!=0): 
      print ("Common Substring ::>",m[match.a: match.a + match.size])  
   else: 
      print ('No longest common sub-string found') 
# Driver program 
if __name__ == "__main__": 
   X = input("Enter first String ")
   Y = input("Enter second String ")
   matchsubstring(X,Y) 

Output

Enter first String pythonprogramming
Enter second String pro
Common Substring ::> pro
raja
Published on 25-Sep-2018 15:26:25
Advertisements