python - Return most frequent letter lowercase and in alphabetical order -


this problem found on internet. mostfrequentletter(s) takes string, s, , returns lowercase string contains occurring letter(s) in alphabetical order. case should ignored (so "a" , "a" considered same function). letters considered (no punctuation or whitespace). not need worry how efficient function is.

so far have this:

def mostfrequentletter(s):             s1 = sorted(s)         s1 = s.lower()            x in s1:         if s1.isalpha == true: 

the frequent letters

from collections import counter  def mostfrequentletter(s):     mc = counter(c c in s.lower() if c.isalpha()).most_common()     return ''.join(sorted(c[0] c in mc if c[1] == mc[0][1])) 

examples:

>>> mostfrequentletter("zgvhyabbv") 'bv' >>> mostfrequentletter("aaabbcc????") 'a' 

the n frequent letters

this provide n frequent letters in string s, sorted in alphabetical order:

from collections import counter  def mostfrequentletter(s, n=1):     ctr = counter(c c in s.lower() if c.isalpha())     return ''.join(sorted(x[0] x in ctr.most_common(n))) 

examples:

>>> mostfrequentletter('aabbccadef?!', n=1) 'a' >>> mostfrequentletter('aabbccadef?!', n=3)  'abc' 

how works

  • c c in s.lower() if c.isalpha()

    this converts string s lower case , letters string.

  • ctr = counter(c c in s.lower() if c.isalpha())

    this creates counter instance letters. use method most_common select common letters. 3 common letters, example, can use:

    >>> data.most_common(3) [('a', 3), ('c', 2), ('b', 2)] 

    in our case, not interested in counts, letters, have manipulate output.

  • x[0] x in ctr.most_common(n)

    this selects n common letters.

  • sorted(x[0] x in ctr.most_common(n))

    this sorts alphabetically n common letters.

  • return ''.join(sorted(x[0] x in ctr.most_common(n)))

    this joins common letters string , returns them.

the frequent letters without using packages

if can't use collections.counter, try:

def mostfrequentletter(s):     d = {}     c in s.lower():         d[c] = d.get(c, 0) + 1     mx = max(dict_values())     return sorted(c c, v in d.items() if v == mx) 

Comments