11

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)
Sunandmoon
  • 287
  • 2
  • 4
  • 9
  • Incidental note: you should read [PEP 8](http://www.python.org/dev/peps/pep-0008/), which documents the recommended Python coding style. Methods should be in snake_case rather than mixedCase. – Chris Morgan Nov 09 '10 at 06:49
  • possible duplicate of [How to find most common elements of a list?](http://stackoverflow.com/questions/3594514/how-to-find-most-common-elements-of-a-list) – kennytm Nov 09 '10 at 06:55
  • possible duplicate of [Python most common element in a list](http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list) – nawfal May 31 '13 at 05:19

11 Answers11

30

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.

Greg Hewgill
  • 828,234
  • 170
  • 1,097
  • 1,237
  • 5
    [`.most_common()`](http://docs.python.org/py3k/library/collections.html#collections.Counter.most_common).... – kennytm Nov 09 '10 at 06:56
  • 1
    Thanks for your answer (you too Chris Morgan), but I guess I forgot to mention that if multiple characters are the most frequent, they should all be output. (ex. 'abcdefg' outputs a = 1, b = 1, etc.) I thought this was the trickiest part, hence the mess at the end. I've edited the question. – Sunandmoon Nov 09 '10 at 07:15
5

If you are using Python 2.7, you can quickly do this by using collections module. collections is a hight performance data structures module. Read more at http://docs.python.org/library/collections.html#counter-objects

>>> from collections import Counter
>>> x = Counter("balloon")
>>> x
Counter({'o': 2, 'a': 1, 'b': 1, 'l': 2, 'n': 1})
>>> x['o']
2
meson10
  • 1,696
  • 13
  • 21
2

Here is way to find the most common character using a dictionary

message = "hello world"
d = {}
letters = set(message)
for l in letters:
    d[message.count(l)] = l

print d[d.keys()[-1]], d.keys()[-1]
kyle k
  • 4,198
  • 7
  • 29
  • 45
1

If you want to have all the characters with the maximum number of counts, then you can do a variation on one of the two ideas proposed so far:

import heapq  # Helps finding the n largest counts
import collections

def find_max_counts(sequence):
    """
    Returns an iterator that produces the (element, count)s with the
    highest number of occurrences in the given sequence.

    In addition, the elements are sorted.
    """

    if len(sequence) == 0:
        raise StopIteration

    counter = collections.defaultdict(int)
    for elmt in sequence:
        counter[elmt] += 1

    counts_heap = [
        (-count, elmt)  # The largest elmt counts are the smallest elmts
        for (elmt, count) in counter.iteritems()]

    heapq.heapify(counts_heap)

    highest_count = counts_heap[0][0]

    while True:

        try:
            (opp_count, elmt) = heapq.heappop(counts_heap)
        except IndexError:
            raise StopIteration

        if opp_count != highest_count:
            raise StopIteration

        yield (elmt, -opp_count)

for (letter, count) in find_max_counts('balloon'):
    print (letter, count)

for (word, count) in find_max_counts(['he', 'lkj', 'he', 'll', 'll']):
    print (word, count)

This yields, for instance:

lebigot@weinberg /tmp % python count.py
('l', 2)
('o', 2)
('he', 2)
('ll', 2)

This works with any sequence: words, but also ['hello', 'hello', 'bonjour'], for instance.

The heapq structure is very efficient at finding the smallest elements of a sequence without sorting it completely. On the other hand, since there are not so many letter in the alphabet, you can probably also run through the sorted list of counts until the maximum count is not found anymore, without this incurring any serious speed loss.

Eric O Lebigot
  • 81,422
  • 40
  • 198
  • 249
1

Question : Most frequent character in a string The maximum occurring character in an input string

Method 1 :

a = "GiniGinaProtijayi"

d ={}
chh = ''
max = 0 
for ch in a : d[ch] = d.get(ch,0) +1 
for val in sorted(d.items(),reverse=True , key = lambda ch : ch[1]):
    chh = ch
    max  = d.get(ch)


print(chh)  
print(max)  

Method 2 :

a = "GiniGinaProtijayi"

max = 0 
chh = ''
count = [0] * 256 
for ch in a : count[ord(ch)] += 1
for ch in a :
    if(count[ord(ch)] > max):
        max = count[ord(ch)] 
        chh = ch

print(chh)        

Method 3 :

import collections

a = "GiniGinaProtijayi"

aa = collections.Counter(a).most_common(1)[0]
print(aa)
Soudipta Dutta
  • 602
  • 6
  • 5
1

I noticed that most of the answers only come back with one item even if there is an equal amount of characters most commonly used. For example "iii 444 yyy 999". There are an equal amount of spaces, i's, 4's, y's, and 9's. The solution should come back with everything, not just the letter i:

sentence = "iii 444 yyy 999"

# Returns the first items value in the list of tuples (i.e) the largest number
# from Counter().most_common()
largest_count: int = Counter(sentence).most_common()[0][1]

# If the tuples value is equal to the largest value, append it to the list
most_common_list: list = [(x, y)
                         for x, y in Counter(sentence).items() if y == largest_count]

print(most_common_count)

# RETURNS
[('i', 3), (' ', 3), ('4', 3), ('y', 3), ('9', 3)]
1

Here's a way using FOR LOOP AND COUNT()

w = input()
r = 1
for i in w:
    p = w.count(i)
    if p > r:
        r = p
        s = i
print(s)
0
def most_frequent(text):
    frequencies = [(c, text.count(c)) for c in set(text)]
    return max(frequencies, key=lambda x: x[1])[0]

s = 'ABBCCCDDDD'
print(most_frequent(s))

frequencies is a list of tuples that count the characters as (character, count). We apply max to the tuples using count's and return that tuple's character. In the event of a tie, this solution will pick only one.

eerock
  • 158
  • 7
0

Here are a few things I'd do:

  • Use collections.defaultdict instead of the dict you initialise manually.
  • Use inbuilt sorting and max functions like max instead of working it out yourself - it's easier.

Here's my final result:

from collections import defaultdict

def find_max_letter_count(word):
    matches = defaultdict(int)  # makes the default value 0

    for char in word:
        matches[char] += 1

    return max(matches.iteritems(), key=lambda x: x[1])

find_max_letter_count('helloworld') == ('l', 3)
Chris Morgan
  • 73,264
  • 19
  • 188
  • 199
  • Nitpicking: `letters` would be more correct as `letter`, since it's a variable that contain exactly one letter. – Eric O Lebigot Nov 09 '10 at 07:53
  • 1
    @EOL: true; I didn't rename that variable from what he had - I'd put it as `char` myself, I think, as it's not just a letter... – Chris Morgan Nov 09 '10 at 21:50
0

The way I did uses no built-in functions from Python itself, only for-loops and if-statements.

def most_common_letter():
    string = str(input())
    letters = set(string)
    if " " in letters:         # If you want to count spaces too, ignore this if-statement
        letters.remove(" ")
    max_count = 0
    freq_letter = []
    for letter in letters:
        count = 0
        for char in string:
            if char == letter:
                count += 1
        if count == max_count:
            max_count = count
            freq_letter.append(letter)
        if count > max_count:
            max_count = count
            freq_letter.clear()
            freq_letter.append(letter)
    return freq_letter, max_count

This ensures you get every letter/character that gets used the most, and not just one. It also returns how often it occurs. Hope this helps :)

-1
#file:filename
#quant:no of frequent words you want

def frequent_letters(file,quant):
    file = open(file)
    file = file.read()
    cnt = Counter
    op = cnt(file).most_common(quant)
    return op   
Josh Anish
  • 51
  • 5
  • Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. Specifically, where did `Counter` come from? – Toby Speight Oct 12 '17 at 10:34
  • Counter has to be imported it is by using the command 'from collections import Counter' – Josh Anish Oct 12 '17 at 11:38
  • Please [edit] your answer to show the additional information, rather than writing it as a comment. Comments can disappear without trace, so it really needs to be part of your answer. Thank you. – Toby Speight Oct 12 '17 at 13:05