第十一届试题G:单词分析

7.单词分析(20)

  • 输入一个字符串,输出(按字典序)出现次数最多的单词及次数

题解

  word = list(input())#读入
  new_word = sorted((set(word)))#把读入的去重并排序,确保了在多个字母出现次数相等的情况下,选择字典序最小的那个字母作为结果。
  max_word = None
  max_count = 0
  for i in new_word:
      if max_count < word.count(i):#对word进行计数并与max_count 比较
          max_word = i #出现次数最多的单词
          max_count = word.count(i)#出现频率最高单词的次数
  print(max_word)
  print(max_count)

PS:1.sorted函数:和sort不同的是:返回一个新的列表(不改变原列表) 用法:sorted(iterable, cmp=None, key=None, reverse=False) 默认 reverse=False按升序排

2.set() 函数:创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

  • 结果

题解:字典+排序

s = input()
dic = {}
for i in range(len(s)):
    if s[i] in dic:
        dic[s[i]] = dic[s[i]] + 1  # 若字典中存在该字母,则出现次数+1
    else:
        dic[s[i]] = 1  # 若字典中不存在该字母。则初始化出现次数为1
dic = sorted(dic.items(), key=lambda x: x[0])  # 按字母字典序排序,dic.items() 用于将字典 dic 转换为一个包含键值对的列表
dic = sorted(dic, key=lambda x: x[1], reverse=True)  # 按出现次数排序
print(dic[0][0])
print(dic[0][1])
posted @ 2021-04-17 16:18  Frommoon  阅读(75)  评论(0编辑  收藏  举报