Python | Comprobar si la string se repite

Mientras trabajamos con strings, muchas veces, podemos encontrarnos con un caso de uso en el que necesitamos encontrar si una string tiene la substring repetida, que se repite en toda la string y, por lo tanto, hace un múltiplo de la substring raíz. Analicemos ciertas formas en las que podemos obtener la substring raíz de una string.

Método n.º 1: uso de la comprensión de listas + fuerza bruta
Podemos realizar esta tarea mediante el corte selectivo y la fuerza bruta. Este es el método ingenuo para encontrar la string en la que tratamos de obtener la raíz de la string mediante la división repetitiva de la string.

# Python3 code to demonstrate working of
# Check if string repeats itself
# Using List comprehension + Brute Force
  
# initializing string 
test_str = "GeeksforGeeksGeeksforGeeksGeeksforGeeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# using List comprehension + Brute Force
# Check if string repeats itself
res = None
for i in range(1, len(test_str)//2 + 1):
    if (not len(test_str) % len(test_str[0:i]) and test_str[0:i] *
           (len(test_str)//len(test_str[0:i])) == test_str):
        res = test_str[0:i]
  
# printing result 
print("The root substring of string : " + res)
Producción :

The original string is : GeeksforGeeksGeeksforGeeksGeeksforGeeks
The root substring of string : GeeksforGeeks

Método n.º 2: usar el corte de lista +find()

Este problema también se puede resolver utilizando el hecho de que podemos buscar la string raíz después de agregar una string y verificar la string raíz en esta string, excepto el último y el primer carácter, que representa que la string se repite.
No funciona para una longitud de string < 2.

# Python3 code to demonstrate working of
# Check if string repeats itself
# Using list slicing + find()
  
# initializing string 
test_str = "GeeksforGeeksGeeksforGeeksGeeksforGeeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# using list slicing + find()
# Check if string repeats itself
res = None
temp = (test_str + test_str).find(test_str, 1, -1)
if temp != -1:
    res = test_str[:temp]
  
# printing result 
print("The root substring of string : " + res)
Producción :

The original string is : GeeksforGeeksGeeksforGeeksGeeksforGeeks
The root substring of string : GeeksforGeeks

Publicación traducida automáticamente

Artículo escrito por manjeet_04 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 *