2014-09-10 41 views
-4

Python 3 - 編寫一個程序,讓用戶輸入一個字符串並顯示字符串中最常出現的字符。Python - 最常見的字符

這是我的嘗試,到目前爲止,我知道這需要大量的工作:

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() 
+6

這是一個非常簡單的事情做到與字典(實際上,有一個特殊的dict子類'collections.Counter',這使得這幾乎是微不足道的) - 你有沒有學過字典呢? – mgilson 2014-09-10 23:44:56

+4

搜索「python字母頻率」,有幾個關於這方面的文章已經有幾個不同的解決方案。 – 2014-09-10 23:45:50

+0

使用[字典](https://docs.python.org/2/tutorial/datastructures.html)(或類似的)來爲每個*字符維護一個*不同的*計數。此外,縮進也很重要。 – user2864740 2014-09-10 23:47:06

回答

-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() 
+0

而不是排序,使用'max'。而不是任何一個,使用'collections.Counter'。 – Veedrac 2014-09-13 19:41:00