【问题标题】:Python - Most Frequent Character [duplicate]Python - 最常见的字符[重复]
【发布时间】:2014-11-04 18:37:11
【问题描述】:

Python 3 - 编写一个程序,让用户输入字符串并显示字符串中出现频率最高的字符。

这是我目前的尝试,我知道它需要做很多工作:

def main():
    count = 0

    my_string = input('Enter a sentence: ')

for ch in my_string:
    if ch == 'A' or ch == 'a':
        count+=1

print('The most popular character appears ', count, 'times.')

main()

【问题讨论】:

  • 用字典很容易做到这一点(事实上,有一个特殊的字典子类collections.Counter 这使得这几乎是微不足道的)——你了解字典了吗?
  • 搜索“python 字母频率”,已经有一些关于这个的帖子有几个不同的解决方案。
  • 使用dictionary(或类似的)来维护每个字符的不同计数。此外,缩进很重要。

标签: python python-3.x


【解决方案1】:

请在下面找到代码:

import collections
def main():
    d = collections.defaultdict(int)
    my_string = input('Enter a sentence: ')
    for c in my_string.strip().lower():
        d[c] += 1
    val=dict(d).values()
    print('The most popular character appears ', sorted(val,reverse=True)[0], 'times.')

main()

【讨论】:

  • 使用max代替排序。而不是任何一个,使用collections.Counter。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多