SequenceMatcher in Python for longest common substring

Python Methods and Functions | String Variables

Examples:

 Input: X = "GeeksforGeeks", Y = "GeeksQuiz" Output: Geeks Input: X = "zxabcdezy", Y = "yzabcdezx" Output: abcdez 

We have a solution to this problem, please refer to

# Function to find the longest common substring

 

from difflib import SequenceMatcher

 

def longestSubstring (str1, str2):

 

# initialize the SequenceMatcher object with

# cc string ode

seqMatch = SequenceMatcher ( None , str1, str2)

 

# match the longest substring

# the output will look 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)

Output:

 Geeks 




Tutorials