Find the most occurring character in a string

Viewed 1006

This piece of code is going to find the most occurring chr in a string ,and it almost works fine through a dictionary ,but unfortunately the problem is that I want to make it return the last key when there are two keys with the same frequency ,but it returns the first one.

And this is what I have done so far:

def most_frequent_letter(s):
    st = s.lower().replace(' ', '')
    frequencies = {}
    for items in st:
        if items in frequencies:
            frequencies[items] += 1
        else:
            frequencies[items] = 1

    return max(frequencies, key=frequencies.get)




most_frequent_letter('mmmaaa')
Out[48]: 'm'

However I don't know how to return 'a' instead of 'm'.

6 Answers

Python max function always returns the first maximum occurrence. Hence, if you always want the last key, then you can just reverse the original string in your code.

def most_frequent_letter(s):
    st = s.lower().replace(' ', '')
    st = st[::-1]
    frequencies = {}
    for items in st:
        if items in frequencies:
            frequencies[items] += 1
        else:
            frequencies[items] = 1

    return max(frequencies, key=frequencies.get)

Or sort the string first if you want the lowest valued key. You can also just create your own max function instead to suit your needs.

def most_frequent_letter(word):
    letters = list(word)
    return (max(set(letters), key = letters.count))

print(most_frequent_letter('mmmaaa'))
# output:m
print(most_frequent_letter('some apples are green'))
# output: e

max() will return the highest value in a list. The key argument takes a single argument function to customize the sort order, in this case, it’s letters.count. The function is applied to each item on the iterable.

letters.count is a built-in function of list. It takes an argument and will count the number of occurrences for that argument. So letters.count('m') will return 3 and letters.count(a) returns 3.

set(test) returns all the unique values from test, so {3, 3}

So what we do in this single line of code is take all the unique values of test, which is {1, 3}. Next, max will apply the list.count function to them and return the maximum value.

Here's a way that creates a reverse frequency dictionary. I also made the creation of the frequency dictionary and its reverse fairly succinct by using a dictionary comprehension:

def most_frequent_letter(s):
    st = s.lower().replace(' ', '')
    frequencies = {}
    frequencies = {item: frequencies.setdefault(item, 0) + 1 for item in st}
    rev_freq = {count: key for key, count in frequencies.items()}
    return rev_freq[max(rev_freq)]

print(most_frequent_letter('nnmmmaaa'))  # -> a

collections library has Counter which does the job for you: We normalize the word with lower casing and replace space before reverse string to have last appearance first.


from collections import Counter

word = 'mmmaaa'
characters = Counter(reversed(word.lower().replace(' ', '')))

# most common 
print(characters.most_common(1))

yes you can get both m and a, it depends how you want to get the output but I have taken a string just for example

def most_frequent_letter(s):
    st = s.lower().replace(' ', '')
    frequencies = {}
    for items in st:
        if items in frequencies:
            frequencies[items] += 1
        else:
            frequencies[items] = 1
    max_val=max(frequencies.values())
    result=""
    for key,value in frequencies.items():
        if value==max_val:
            result+=key

    return result


result=most_frequent_letter('mmmaaa')
print(result)

the output will be "ma"

In python when you use the max function it will return the first max frequency, if you want the second max frequency you could try to delete from the list the 'm's so after that the first max frequency will be 'a'.

Related