SequenceMatcher en Python para la substring común más larga

Dadas dos strings ‘X’ e ‘Y’, imprima la substring común más larga.

Ejemplos:

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

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

Tenemos una solución existente para este problema, consulte Imprima el enlace de substring común más largo . Resolveremos el problema en python usando el método SequenceMatcher.find_longest_match().

¿Cómo funciona el método SequenceMatcher.find_longest_match(aLow,aHigh,bLow,bHigh)?

Primero inicializamos el objeto SequenceMatcher con dos strings de entrada str1 y str2, find_longest_match(aLow,aHigh,bLow,bHigh) toma 4 parámetros aLow, bLow son el índice de inicio de la primera y la segunda string respectivamente y aHigh, bHigh son la longitud de la primera y la segunda string respectivamente . find_longest_match() devuelve una tupla nombrada (i, j, k) tal que a[i:i+k] es igual a b[j:j+k], si ningún bloque coincide, esto devuelve (aLow, bLow, 0).

# 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)

Producción:

Geeks

Publicación traducida automáticamente

Artículo escrito por Shashank Mishra y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *