python – Most frequent symbol


I want to make sure that I enter a word and write to me the symbol that appears in the word most often. It does not enter my head how you can do this. Please, help. For example, we have a word: priority. We must deduce that the most frequent symbol is, etc. It does not need it to write the number, but only to display the symbol.


from collections import Counter

word = 'приоритет'
c = Counter(word)

Because the most_common method returns a list of the most frequent values ​​(even if we asked for one most frequent value), then we need to take the first element (this requires the first [0] ). Each item in this list is a pair (элемент, количество) , so you need to take the first item again.

In general, in the word "priority" there are 3 letters that occur twice (p, u, t), it will display only one of them (it displayed "p" for me).

Alternative solution without using Counter :

word = 'приоритет'

# Подсчитываем количество вхождений каждой буквы в слове
c = dict()

for letter in word:
    c[letter] = c.get(letter, 0) + 1
    # .get(letter, 0) вернет значение по ключу letter или 0, если такого ключа нет

print(c)  # {'п': 1, 'р': 2, 'и': 2, 'о': 1, 'т': 2, 'е': 1}

# Выводим ключ, которому соответствует наибольшее из значений
# (точнее, один из таких ключей)
print(max(c.items(), key=lambda item: item[1])[0])  # р
Scroll to Top