The second provincial match of the 11th Blue Bridge Cup python group-word analysis

1. Problem description:
Xiaolan is learning a magical language. The words in this language are composed of lowercase English letters. Some words are very long, far exceeding the length of normal English words. Xiaolan had been learning for a long time and couldn't remember some words. He planned not to remember these words completely, but to distinguish words based on which letter appeared the most. Now, please help Xiaolan. After giving a word, help him find the most frequent letter and the number of times this letter appears.
[Input format] The 
input line contains one word, and the word is only composed of lowercase English letters.
[Output format] Output two lines, the first line contains an English letter, which indicates which letter appears most frequently in the word. If there are multiple letters that appear the same number of times, the one with the smallest lexicographic order is output. The second line contains an integer that represents the number of times the most frequent letter appears in the word.
[Sample input] lanqiao
[Sample output]
a
2
[Sample input] longlonglongistoolong
[Sample output]
o
6
[Evaluation use case scale and conventions] For all evaluation use cases, the input word length should not exceed 1000.

2. Thinking analysis:

Analyzing the question, we can know that we count the characters that appear when we traverse the string. For the python language, we can use the dictionary to count. You can use the collections.defaultdict(int) method to define the value of the dictionary as an int type (the collections module has many Dictionary, deque, tuple, etc.), so that if the key does not exist when counting, it will be automatically initialized to 0. After the count is over, the dictionary is sorted according to the value from large to small, and the final output is sorted. The first key and value of

3. The code is as follows:

import collections

if __name__ == '__main__':
    # 很明显使用python中的字典对其进行计数即可, 使用defaultdict(int)方法当键不存在的时候那么会自动初始化为0
    dic = collections.defaultdict(int)
    s = input()
    for c in s:
        dic[c] += 1
    # 使用lambda表达式对字典进行排序, x[1]表示按照值进行排序, reverse表示从大到小排序
    dic = sorted(dic.items(), key=lambda x: x[1], reverse=True)
    print(dic[0][0])
    print(dic[0][1])

 

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/114979334