Dada una string, la tarea es escribir un programa en Python que imprima el número de ocurrencias de cada carácter en una string.
Hay varias formas en Python, podemos hacer esta tarea. Analicemos algunos de ellos.
Método #1: Usar set()
+count()
Iterar sobre la string convertida establecida y obtener el recuento de cada carácter en la string original.
# Python3 code to program to find occurrence # to each character in given string # initializing string inp_str = "GeeksforGeeks" # using set() + count() to get count # of each element in string out = {x : inp_str.count(x) for x in set(inp_str )} # printing result print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(out))
Producción:
Occurrence of all characters in GeeksforGeeks is : {'o': 1, 'r': 1, 'e': 4, 's': 2, 'f': 1, 'G': 2, 'k': 2}
Método #2: Usando el diccionario
# Python3 code to program to find occurrence # to each character in given string # initializing string inp_str = "GeeksforGeeks" # frequency dictionary freq = {} for ele in inp_str: if ele in freq: freq[ele] += 1 else: freq[ele] = 1 # printing result print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(freq))
Producción:
Occurrence of all characters in GeeksforGeeks is : {'e': 4, 'r': 1, 'o': 1, 'f': 1, 'G': 2, 's': 2, 'k': 2}
Método #3: Usarcollections
# Python3 code to program to find occurrence # to each character in given string from collections import Counter # initializing string in_str = "GeeksforGeeks" # using collections.Counter() to get # count of each element in string oup = Counter(in_str) # printing result print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(oup))
Producción:
Occurrence of all characters in GeeksforGeeks is : Counter({'e': 4, 's': 2, 'G': 2, 'k': 2, 'f': 1, 'r': 1, 'o': 1})