我在stackoverflow上看到一份工作招聘信息时发现了这个编程问题。作为一个初学者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)