from collections import Counter
def myFunction(myDict):
myMax = 0 # Keep track of the max frequence
myResult = [] # A list for return
for key in myDict:
print('The key is', key, ', The count is', myDict[key])
print('My max is:', myMax)
# Finding out the max frequence
if myDict[key] >= myMax:
if myDict[key] == myMax:
myMax = myDict[key]
myResult.append(key)
# Case when it is greater than, we will delete and append
else:
myMax = myDict[key]
del myResult[:]
myResult.append(key)
return myResult
foo = ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
myCount = Counter(foo)
print(myCount)
print(myFunction(myCount))
Salida:
The list: ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
Counter({'1': 3, '2': 3, '10': 1, '5': 1, '7': 1, '6': 1})
The key is 10 , The count is 1
My max is: 0
The key is 1 , The count is 3
My max is: 1
The key is 2 , The count is 3
My max is: 3
The key is 5 , The count is 1
My max is: 3
The key is 7 , The count is 1
My max is: 3
The key is 6 , The count is 1
My max is: 3
['1', '2']
de escribir este sencillo programa, creo que también podría funcionar. No estaba al tanto de la función most_common()
hasta que realizo una búsqueda. Creo que esto dará como resultado el elemento más frecuente que existe, funciona comparando el elemento máximo frecuente, cuando veo un elemento más frecuente, borra la lista de resultados y la agrega una vez; o si es la misma frecuencia, simplemente se agrega a ella. Y continúa hasta que todo el contador se repita.
¿Qué hay de veces cuando hay 3 números repetidos, como [ '1', '1', '2' '2', '8', '7', '7'] ... tu script no funcionará para eso. Gracias, de lo contrario, la solución es buena. –
@james: No se puede reproducir, devuelve 'set (['1', '2', '7'])' para mí con ambos fragmentos de código. –
Ah sí, no hay problema, está funcionando bien para mí ahora. Muchas gracias. –