burizz
burizz

Reputation: 1

Finds the most frequent char in a string with python

I have written the bellow function to find the most frequent occurrences of a char in a string, it works well with :

  1. "Hello World!"
  2. "How do you do?"
  3. "One" ( returns the first alphabetic char if the string has unique letters only )

It fails on the following string "Lorem ipsum dolor sit amet". The most frequent letters are all with 3 occurrences and it results in a blank string instead of giving me one of them ( it should give the first one in alphabetical order )

def frequent_char(text):

    charset = ''.join(sorted(text))

    maxcount = 0
    maxchar = None

    for item in charset.lower():
        charcount = text.count(item)

        if charcount > maxcount :
            maxcount = charcount
            maxchar = item

    return maxchar

I don't what mistake I am making within the code. Can anyone help?

Upvotes: 0

Views: 8739

Answers (3)

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22952

An elegant solution is to use collections.Counter, see: http://docs.python.org/2/library/collections.html#counter-objects

>>> counter = Counter('Lorem ipsum dolor sit amet')

The most frequent occurrences of a char is:

>>> counter.most_common(1)
[(' ', 4)]

If you don't care about space:

>>> counter.most_common(2)[1]
('m', 3)

Simple!

Upvotes: 2

user1907906
user1907906

Reputation:

The space has four occurences in Lorem ipsum dolor sit amet.

So if your problem is

to find the most frequent occurrences of a char in a string

your function works like a charm.

Edit:

Since you use both 'char' and 'letter' in your question it is not completely clear what you are asking. Since a 'char' is a much easier notion than a 'letter' in Python, I decided to interpret your question as a question about chars.

Upvotes: 5

jramirez
jramirez

Reputation: 8685

Remove all white spaces from string for it to work.

def frequent_char(text):

    charset = ''.join(sorted(text))
    textTmp = text.replace(" ", "")  # add this to remove spaces
    maxcount = 0
    maxchar = None
    for item in charset.lower():
        charcount = textTmp.count(item)

        if charcount > maxcount:
            maxcount = charcount
            maxchar = item

return maxchar

Upvotes: 0

Related Questions