Most common letter in word Python

Question:

I need to get the most common letter of given word. Well, that’s what i need

Find the most common letter in the given word. If any letters repeat the same times, output the less symbol. (word1 < word2)

word = input()
repeats = 1
for i in word:
    p = word.count(i)
    if p > repeats:
        repeats = p
        res = i

I can’t do the last task

If any letters repeat the same times, output the less symbol. (word1 < word2)

Asked By: Autom

||

Answers:

You can use Counter here,

In [1]: from collections import Counter

In [2]: Counter('most common letter of given word').most_common(1)
Out[2]: [('o', 5)]
Answered By: Rahul K P
word = input().lower()
counter_list = []
letters = "abcdefghijklmnopqrstuvwxyz"
for l in letters:
    counter_list.append(word.count(l))

i = counter_list.index(max(counter_list))
print(letters[i])

    
Answered By: Nick

You have to use list or better set to keep all chars with the same count.
And later you can use min() to get correct result from list or set:

#word = input()
word = 'testsample'

repeats = 0

for char in word:
    count = word.count(char)
    #print(char, count)
    
    if count > repeats:
        repeats = count
        result = set(char)  # create new `set()`
        #result = [char]    # create new `list()`
    elif count == repeats:
        result.add(char)      # add to existing `set()`
        #result.append(char)  # add to existing `list()`
        
print('all:', result)
        
print('min:', min(result))

Result:

all: {'s', 'e', 't'}
min: e
Answered By: furas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.