SequenceMatcher in Python for Longest Common Substring

Given two strings ‘X’ and ‘Y’, print the longest common sub-string.

Examples:

Input :  X = "GeeksforGeeks", 
         Y = "GeeksQuiz"
Output : Geeks

Input : X = "zxabcdezy", 
        Y = "yzabcdezx"
Output : abcdez



We have existing solution for this problem please refer Print the longest common substring link. We will solve problem in python using SequenceMatcher.find_longest_match() method.

How SequenceMatcher.find_longest_match(aLow,aHigh,bLow,bHigh) method works ?

First we initialize SequenceMatcher object with two input string str1 and str2, find_longest_match(aLow,aHigh,bLow,bHigh) takes 4 parameters aLow, bLow are start index of first and second string respectively and aHigh, bHigh are length of first and second string respectively. find_longest_match() returns named tuple (i, j, k) such that a[i:i+k] is equal to b[j:j+k], if no blocks match, this returns (aLow, bLow, 0).

filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to find Longest Common Sub-string
  
from difflib import SequenceMatcher
  
def longestSubstring(str1,str2):
  
     # initialize SequenceMatcher object with 
     # input string
     seqMatch = SequenceMatcher(None,str1,str2)
  
     # find match of longest sub-string
     # output will be like Match(a=0, b=0, size=5)
     match = seqMatch.find_longest_match(0, len(str1), 0, len(str2))
  
     # print longest substring
     if (match.size!=0):
          print (str1[match.a: match.a + match.size]) 
     else:
          print ('No longest common sub-string found')
  
# Driver program
if __name__ == "__main__":
    str1 = 'GeeksforGeeks'
    str2 = 'GeeksQuiz'
    longestSubstring(str1,str2)

chevron_right


Output:

Geeks


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.