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:

JavaScript

Output:

JavaScript

Updated example:

JavaScript

Advertisement

Answer

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

JavaScript

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

JavaScript

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