[Python] Checkio Solution 解答 - The Most Wanted Letter



You are given a text, which contains different english letters and punctuation symbols. You should find the most frequent letter in the text. The letter returned must be in lower case.
While checking for the most wanted letter, casing does not matter, so for the purpose of your search, "A" == "a". Make sure you do not count punctuation symbols, digits and whitespaces, only letters.

If you have two or more letters with the same frequency, then return the letter which comes first in the latin alphabet. For example -- "one" contains "o", "n", "e" only once for each, thus we choose "e".






A text for analysis as a string.



The most frequent letter in lower case as a string.



A text contains only ASCII symbols.
0 < len(text) ≤ 105


Source: https://py.checkio.org

My Solution:

def checkio(text): 
  text = text.lower() 
  valids = "" 
  for character in text: 
    if character.isalpha(): 
      valids += character 
  d = {} 
  for i in range(len(valids)): 
    if not valids[i] in d: 
      tcount = valids.count(valids[i]) 
      d[valids[i]] = tcount 
    i += 1 
  highest_freq = max(d.values()) 
  most_wanted = [] 
  for letter, freq in zip(d.keys(),d.values()): 
    if freq == highest_freq: 
  alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] 
  if len(most_wanted) == 1: 
    return most_wanted[0] 
    beta = [] 
    for j in range(len(most_wanted)): 
      j += 1 
    return alpha[min(beta)]


My first game on Checkio. I hadn't had a complete beginner course at that time. So this solution is not precise enough. I should have imported the string module and use string.ascii_lowercase, instead of typing all alphabets into a list.

Copyright © Vantopics