我在查看SO上的职位发布时发现了这个编程问题.我认为它非常有趣,作为一名初学Python程序员,我试图解决它.但是我觉得我的解决方案非常……凌乱……任何人都可以提出任何建议来优化它或使其更清洁吗?我知道这很琐碎,但我写得很开心.注意:Python 2.6
问题:
为函数写入伪代码(或实际代码),该函数接收字符串并返回该字符串中出现最多的字母.
我的尝试:
import string
def find_max_letter_count(word):
alphabet = string.ascii_lowercase
dictionary = {}
for letters in alphabet:
dictionary[letters] = 0
for letters in word:
dictionary[letters] += 1
dictionary = sorted(dictionary.items(),
reverse=True,
key=lambda x: x[1])
for position in range(0, 26):
print dictionary[position]
if position != len(dictionary) - 1:
if dictionary[position + 1][1] < dictionary[position][1]:
break
find_max_letter_count("helloworld")
输出:
>>>
('l', 3)
更新示例:
find_max_letter_count("balloon")
>>>
('l', 2)
('o', 2)