Skip to content
Advertisement

Finding the most frequent character in a string

I found this programming problem while looking at a job posting on SO. I thought it was pretty interesting and as a beginner Python programmer I attempted to tackle it. However I feel my solution is quite…messy…can anyone make any suggestions to optimize it or make it cleaner? I know it’s pretty trivial, but I had fun writing it. Note: Python 2.6

The problem:

Write pseudo-code (or actual code) for a function that takes in a string and returns the letter that appears the most in that string.

My attempt:

import string

def find_max_letter_count(word):

    alphabet = string.ascii_lowercase
    dictionary = {}

    for letters in alphabet:
        dictionary[letters] = 0

    for letters in word:
        dictionary[letters] += 1

    dictionary = sorted(dictionary.items(), 
                        reverse=True, 
                        key=lambda x: x[1])

    for position in range(0, 26):
        print dictionary[position]
        if position != len(dictionary) - 1:
            if dictionary[position + 1][1] < dictionary[position][1]:
                break

find_max_letter_count("helloworld")

Output:

>>> 
('l', 3)

Updated example:

find_max_letter_count("balloon") 
>>>
('l', 2)
('o', 2)

Advertisement

Answer

There are many ways to do this shorter. For example, you can use the Counter class (in Python 2.7 or later):

import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])

If you don’t have that, you can do the tally manually (2.5 or later has defaultdict):

d = collections.defaultdict(int)
for c in s:
    d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])

Having said that, there’s nothing too terribly wrong with your implementation.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement