Python | Formas de verificar que la string contenga todos los mismos caracteres

Dada una lista de strings, escriba un programa en Python para verificar si cada string tiene todos los caracteres iguales o no. A continuación se presentan algunos métodos para verificar lo mismo.

Método n.º 1: uso del método ingenuo [ineficiente]

# Python code to demonstrate 
# to check whether string contains
# all characters same or not
  
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
  
# Printing initial string
print ("Initial Strings list", ini_list)
  
# Using Naive Method:
flag = True
for i in ini_list:
    for j in range(0, len(i)-1):
        if i[j]!= i[j + 1]:
            print ("String {} don't have all characters same".format(i))
            flag = False
            break
    if flag == True:
        print ("String {} don't have all characters same".format(i))
         
Producción:

Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa don't have all characters same
String aaaaaaabaa don't have all characters same

 
Método n.º 2: uso de comparaciones de strings

# Python code to demonstrate 
# to check whether string contains
# all characters same or not
  
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
  
# Printing initial string
print ("Initial Strings list", ini_list)
  
# Using String comparison
for i in ini_list:
    if i == len(i)*i[0]:
        print ("String {} have all characters same".format(i))
    else:
        print ("String {} don't have all characters same".format(i))
         
Producción:

Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same

 
Método n.° 3: usar la comparación de conteo

# Python code to demonstrate 
# to check whether string contains
# all characters same or not
  
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
  
# Printing initial string
print ("Initial Strings list", ini_list)
  
# Using String comparison
for i in ini_list:
    if i.count(i[0]) == len(i):
        print ("String {} have all characters same".format(i))
    else:
        print ("String {} don't have all characters same".format(i))
         
Producción:

Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same

Publicación traducida automáticamente

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