5. mostFrequentLetters(s) 13 pts] Write the function mostFrequentLetters(s), tha
ID: 3910990 • Letter: 5
Question
5. mostFrequentLetters(s) 13 pts] Write the function mostFrequentLetters(s), that takes a string s, and ignoring case (so "A" and "a" are treated the same),returns a lowercase string containing the letters of s in most frequently used order. (In the event of a tie between two letters, follow alphabetic order.) So mostFrequentLetters("We Attack at Dawn") returns "atwcdekn". Note that digits, punctuation, and whitespace are not letters! Also note that seeing as we have not yet covered lists, sets, maps, or efficiency, you are not expected to write the most efficient solution. (And you should not use lists, sets, or maps in your solution. Do not use sorted0 or .sort0 either.) Finally, if s does not contain any alphabetic characters, the result should be the empty string)Explanation / Answer
Please let me know if you have any doubts or you want me to modify the code. And if you find this code useful then don't forget to rate my answer as thumps up. Thank you! :)
def mostFrequentLetters(s):
# makes every character lower case
s = s.lower()
answer = ''
# eliminates all chars that aren't strings
for c in s:
if not c.isalpha():
s = s.replace(c, '')
# if there arent any alphabetic chars, return ""
if not s: return ""
# repeatedly find the char with largest count
# and add it to answer
# then eliminate that char from the string
while s:
answer += mostCommonChar(s)
s = s.replace(mostCommonChar(s), '')
return answer
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.