Home > OS >  Most common letter in word Python
Most common letter in word Python

Time:10-09

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)

CodePudding user response:

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])

    

CodePudding user response:

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)]

CodePudding user response:

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
  • Related