在字符串中查找最频繁的字符
我在看一个工作招聘信息的时候发现了这个编程问题。我觉得这个问题挺有意思的,作为一个初学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)
19 个回答
2
这里有一种方法可以通过字典找到出现频率最高的字符。
message = "hello world"
d = {}
letters = set(message)
for l in letters:
d[message.count(l)] = l
print d[d.keys()[-1]], d.keys()[-1]
5
如果你在使用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
37
有很多方法可以让这个过程变得更简单。例如,你可以使用Counter
类(在Python 2.7或更高版本中可以使用):
import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])
如果你没有这个类,你也可以手动进行统计(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])
不过,值得一提的是,你的实现方式并没有什么太大的问题。