Sun*_*oon 9 python algorithm optimization time-complexity
我在查看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")
Run Code Online (Sandbox Code Playgroud)
输出:
>>>
('l', 3)
Run Code Online (Sandbox Code Playgroud)
更新示例:
find_max_letter_count("balloon")
>>>
('l', 2)
('o', 2)
Run Code Online (Sandbox Code Playgroud)
Gre*_*ill 22
有很多方法可以做到这一点.例如,您可以使用Counter
该类(在Python 2.7或更高版本中):
import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])
Run Code Online (Sandbox Code Playgroud)
如果你没有,你可以手动进行计数(2.5或更高版本defaultdict
):
d = collections.defaultdict(int)
for c in s:
d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])
Run Code Online (Sandbox Code Playgroud)
话虽如此,你的实施并没有太严重的错误.
如果您使用的是 Python 2.7,您可以使用 collections 模块快速完成此操作。collections 是一个高性能的数据结构模块。在http://docs.python.org/library/collections.html#counter-objects阅读更多
>>> from collections import Counter
>>> x = Counter("balloon")
>>> x
Counter({'o': 2, 'a': 1, 'b': 1, 'l': 2, 'n': 1})
>>> x['o']
2
Run Code Online (Sandbox Code Playgroud)