Dada una lista, la tarea es encontrar si algún elemento aparece ‘n’ veces en una lista dada de enteros. Básicamente, comprobará el primer elemento que se produce n veces.
Ejemplos:
Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3 Output : 2 Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4 Output : 1
A continuación se muestran algunos métodos para realizar la tarea en Python:
método 1: uso de iteración y clasificación simples
Python3
# Python code to find occurrence of any element # appearing 'n' times # Input Initialisation input = [1, 2, 3, 0, 4, 3, 4, 0, 0] # Sort Input input.sort() # Constants Declaration n = 3 prev = -1 count = 0 flag = 0 # Iterating for item in input: if item == prev: count = count + 1 else: count = 1 prev = item if count == n: flag = 1 print("There are {} occurrences of {} in {}".format(n, item, input)) break # If no element is not found. if flag == 0: print("No occurrences found")
Producción :
There are 3 occurrences of 0 in [0, 0, 0, 1, 2, 3, 3, 4, 4]
Método 2: Usando Count
Python3
# Python code to find occurrence of any element # appearing 'n' times # Input list initialisation input = [1, 2, 3, 4, 0, 4, 3, 4] # Constant declaration n = 3 # print print("There are {} occurrences of {} in {}".format(input.count(n), n, input))
Producción :
There are 2 occurrences of 3 in [1, 2, 3, 4, 0, 4, 3, 4]
Método 3: Usando defaultdict
Primero llenamos el elemento de la lista en un diccionario y luego encontramos si el recuento de cualquier elemento es igual a n.
Python3
# Python code to find occurrence of any element # appearing 'n' times # importing from collections import defaultdict # Dictionary declaration dic = defaultdict(int) # Input list initialisation Input = [9, 8, 7, 6, 5, 9, 2] # Dictionary populate for i in Input: dic[i]+= 1 # constant declaration n = 2 flag = 0 # Finding from dictionary for element in Input: if element in dic.keys() and dic[element] == n: print("Yes, {} has {} occurrence in {}.".format(element, n, Input)) flag = 1 break # if element not found. if flag == 0: print("No occurrences found")
Producción :
Yes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2]
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA