String dada str. La tarea es verificar si es una string binaria o no.
Ejemplos:
Input: str = "01010101010" Output: Yes Input: str = "geeks101" Output: No
Enfoque 1 : Uso de Set
- Inserta la string dada en un conjunto
- Compruebe si los caracteres establecidos constan de 1 y/o 0 solamente.
Ejemplo:
Python3
# Python program to check # if a string is binary or not # function for checking the # string is accepted or not def check(string): # set function convert string # into set of characters . p = set(string) # declare set of '0', '1' . s = {'0', '1'} # check set p is same as set s # or set p contains only '0' # or set p contains only '1' # or not, if any one condition # is true then string is accepted # otherwise not . if s == p or p == {'0'} or p == {'1'}: print("Yes") else: print("No") # driver code if __name__ == "__main__": string = "101010000111" # function calling check(string)
Producción
Yes
Enfoque 2: iteración simple
- Iterar para cada carácter y verificar si el carácter es 0 o 1.
- Si no es así, establezca un contador y rompa.
- Después de la iteración, compruebe si el contador está configurado o no.
Python3
# Python program to check # if a string is binary or not # function for checking the # string is accepted or not def check2(string): # initialize the variable t # with '01' string t = '01' # initialize the variable count # with 0 value count = 0 # looping through each character # of the string . for char in string: # check the character is present in # string t or not. # if this condition is true # assign 1 to the count variable # and break out of the for loop # otherwise pass if char not in t: count = 1 break else: pass # after coming out of the loop # check value of count is non-zero or not # if the value is non-zero the en condition is true # and string is not accepted # otherwise string is accepted if count: print("No") else: print("Yes") # driver code if __name__ == "__main__": string = "001021010001010" # function calling check2(string)
Producción
No
Enfoque 3 : expresiones regulares
- Compile una expresión regular usando compile() para «el carácter no es 0 o 1».
- Use re.findall() para obtener las strings que satisfacen la expresión regular anterior.
- Imprimir salida basada en el resultado.
Python3
#import library import re sampleInput = "1001010" # regular expression to find the strings # which have characters other than 0 and 1 c = re.compile('[^01]') # use findall() to get the list of strings # that have characters other than 0 and 1. if(len(c.findall(sampleInput))): print("No") # if length of list > 0 then it is not binary else: print("Yes") # if length of list = 0 then it is binary
Producción
Yes
Enfoque 4: Uso del manejo de excepciones e int
Python tiene un método incorporado para convertir una string de una base específica a un entero decimal, usando int(string, base) . Si la string pasada como argumento no tiene la base especificada, se genera un ValueError.
Python3
# Python program to check # if a string is binary or not # function for checking the # string is accepted or not def check(string): try: # this will raise value error if # string is not of base 2 int(string, 2) except ValueError: return "No" return "Yes" # driver code if __name__ == "__main__": string1 = "101011000111" string2 = "201000001" # function calling print(check(string1)) print(check(string2)) # this code is contributed by phasing17
Producción
Yes No
Complejidad de Tiempo: O(1), Espacio Auxiliar: O(1)
Enfoque 5: Uso de la función de conteo()
Python3
string = "01010101010" if(string.count('0')+string.count('1')==len(string)): print("Yes") else: print("No")
Producción
Yes
Publicación traducida automáticamente
Artículo escrito por priyankamaurya y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA