【发布时间】:2011-05-07 01:52:15
【问题描述】:
我在查看 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)
【问题讨论】:
-
附带说明:您应该阅读PEP 8,它记录了推荐的 Python 编码风格。方法应该是snake_case而不是mixedCase。
标签: python algorithm optimization time-complexity