I am doing an exercise the requires me to return the most frequent letter in a string of letters. In the event that there are two letters that appear with the same frequency, the 'tiebreaker' is whichever appears first in the alphabet. For example:
'aaaabbbb' #should return a.
My code to return the letter is below. I recognize that it may not be the most efficient. I'll worry about that later.
def mostWantedLetter(text):
text = text.lower()
mwl = {}
for letter in text:
if letter not in mwl:
mwl[letter] = 1
else:
mwl[letter] += 1
for letter in sorted(mwl, key = mwl.get, reverse = True):
if letter.isalpha():
#letter = sorted(list(letter))
return letter #[0]
Thank you to the Stack Overflow community for your help in getting me this far!
Congratulations on making it thus far. I'll offer two hints:
Hint 1: modify the key
argument to sorted()
to take into account both the letter's count and its position in the alphabet.
Hint 2: look into how Python compares tuples.
On a separate note, collections.Counter
and collections.defaultdict
are worth knowing about.
Right, I found this and it was pretty damn cool:
>>> import collections
>>>
>>> ordered1 = collections.Counter('aaaabbbb').most_common(1))
>>> ordered1[0][0]
'a'
>>>
>>> ordered2 = collections.Counter('abb').most_common(1))
>>> ordered2[0][0]
'b'
This puts letters in order primarily of occurrence, and then if two letters occur equal times then they are sorted alphabetically.
def mostWantedLetter(text):
# count how many times each letter occurs
mwl = {}
for ch in text.lower():
if ch.isalpha():
mwl[ch] = mwl.get(ch, 0) + 1
# ordered descending by count (highest first) then ascending by letter
least = min(mwl.items(), key=lambda x:(-x[1], x[0]))
# return the letter from the least item
return least[0]
def most_wanted(s):
return chr(min(set([ord(x) for x in list(s)])))
It breaks the string into a list and then converts them all to their ascii representation. It makes this a set so that duplicates don't need to be compared. It takes the minimum value from these and then converts it back to a letter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.