redbook0301
redbook0301

Reputation: 11

one or more most frequent letter in string python

The question asks me to return a string in lowercase with the most frequently occurring letter(s) in s in alphabetical order. So far I have:

def mostFrequentLetter(s):
    allchar = ''.join(sorted(s))
    temp = s.replace(" ","")
    max = None
    maxchar = None
    for alph in allchar.lower():
        charcount = temp.count(alph)
        if alph not in string.ascii_letters: continue
        elif charcount > max:
            max = charcount
            max = alph
        elif charcount == max:
            max2 = charcount            
            max2 = alph
            max.append(max2)
    return max

If I put in 'aaaabbbb' it should give me 'ab' but it only gives me 'a'. How do I fix this?

Upvotes: 1

Views: 733

Answers (4)

juanmajmjr
juanmajmjr

Reputation: 1163

Here, the solution which is adapted to the code you offered and without using a Set :)

def mostFrequentLetter(s):
    allchar = ''.join(sorted(s))
    temp = s.replace(" ","")
    max = None
    maxchar = None
    for alph in allchar.lower():
        charcount = temp.count(alph)
        if alph not in string.ascii_letters: continue
        elif charcount > maxchar:
            maxchar= charcount
            max= alph
        elif charcount == maxchar and alph not in max:          
            max+=alph
    return max

Upvotes: 0

Akshat Harit
Akshat Harit

Reputation: 824

The other answers are more pythonic. For your code though there are a few mistakes you made. See them in the comments of the following code

def mostFrequentLetter(s):
    allchar = ''.join(sorted(s))
    temp = s.replace(" ","")
    max = None
    maxchar = ""
    for alph in set(allchar.lower()):
        charcount = temp.count(alph)
        if alph not in string.ascii_letters: continue
        elif charcount > max:
            max = charcount
            maxchar+=alph #max = alph sets max as alph. You need to
                          #append the maximum occuring character, not set it as max
        elif charcount == max:
            maxchar+=alph  # max2 is not really needed. Its not being used anywhere else.
                           # In fact this whole clause can be refactored by setting charcount >= max above.
                           # I am still leaving it to be in line with what you wrote
    return maxchar

print mostFrequentLetter("aaaabbbb")

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

You could use the builtin collections.Counter:

from collections import Counter

def most_frequent_letter(s):
    counter = Counter(s)
    letter, max_count = next(counter.most_common())
    letters = sorted(letter
                     for letter, count in counter.most_common()
                     if count == max_count)
    return ''.join(letters)

If you can't use Counter for some reason, you could use a default dictionary:

from collections import defaultdict

def most_frequent_letter(s):
    counter = defaultdict(int)
    for char in s:
        counter[char] += 1
    max_count = max(counter.values())
    letters = sorted(letter
                     for letter, count in counter.items()
                     if count == max_count)
    return ''.join(letters)

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

I recommend using the set() function so that you're not checking repeated characters multiple times.

def mostFrequentLetter(s):
    return ''.join(sorted(sorted((c for c in set(s) if c in string.ascii_letters), key=s.count, reverse=True)[:2]))

This first turns the string into a set, eliminating duplicates. It then sorts that set according to how often each element appears in the original string, in reverse (descending) order. Finally, it joins the sorted elements into a single string and returns it.

>>> s = 'abbbbbbbbccddddddddddddddddd'
>>> mostFrequentLetter(s)
'bd'

Upvotes: 0

Related Questions