Return the most common letter in lowercase and alphabetical order
This is the problem I found on the internet. mostFrequentLetter (s) Takes a string, s, and returns a lowercase string containing the most common letters (s) in alphabetical order. The case should be ignored (so "A" and "a" are considered the same for this function). Only letters will be considered (no punctuation marks or spaces). You don't need to worry about how effective this feature is.
So far I have this:
def mostFrequentLetter(s):
s1 = sorted(s)
s1 = s.lower()
for x in s1:
if s1.isAlpha == True:
source to share
Most frequent letters
from collections import Counter
def mostFrequentLetter(s):
mc = Counter(c for c in s.lower() if c.isalpha()).most_common()
return ''.join(sorted(c[0] for c in mc if c[1] == mc[0][1]))
Examples:
>>> mostFrequentLetter("ZgVhyaBbv")
'bv'
>>> mostFrequentLetter("aaabbcc????")
'a'
Most frequent letters n
This will provide the n
most frequent letters in the string s
, sorted alphabetically:
from collections import Counter
def mostFrequentLetter(s, n=1):
ctr = Counter(c for c in s.lower() if c.isalpha())
return ''.join(sorted(x[0] for x in ctr.most_common(n)))
Examples:
>>> mostFrequentLetter('aabbccadef?!', n=1)
'a'
>>> mostFrequentLetter('aabbccadef?!', n=3)
'abc'
How it works
-
c for c in s.lower() if c.isalpha()
This will convert the string
s
to lowercase and then only the letters from that string. -
ctr = Counter(c for c in s.lower() if c.isalpha())
This creates a Counter instance for those letters. We will use a method
most_common
to select the most common letters. For example, to get the three most common letters, we can use:>>> data.most_common(3) [('a', 3), ('c', 2), ('b', 2)]
In our case, we are not interested in numbers, only letters, so we have to manipulate this output.
-
x[0] for x in ctr.most_common(n)
This selects the
n
most common letters. -
sorted(x[0] for x in ctr.most_common(n))
This sorts the most common letters alphabetically
n
. -
return ''.join(sorted(x[0] for x in ctr.most_common(n)))
This concatenates the most common letters into a string and returns them.
Most common letters without using packages
If we can't use collections.Counter
, try:
def mostFrequentLetter(s):
d = {}
for c in s.lower():
d[c] = d.get(c, 0) + 1
mx = max(dict_values())
return sorted(c for c, v in d.items() if v == mx)
source to share