查找字符串中出现频率最高的字符 [英] Finding the most frequent character in a string
问题描述
我在查看 SO 上的招聘信息时发现了这个编程问题.我认为这很有趣,作为初学者的 Python 程序员,我试图解决它.但是我觉得我的解决方案非常......凌乱......任何人都可以提出任何建议来优化它或使其更干净吗?我知道这很琐碎,但我写得很开心.注意:Python 2.6
问题:
为接受字符串并返回该字符串中出现次数最多的字母的函数编写伪代码(或实际代码).
我的尝试:
导入字符串def find_max_letter_count(word):字母表 = string.ascii_lowercase字典 = {}对于字母表中的字母:字典[字母] = 0对于单词中的字母:字典[字母] += 1字典 = 排序(字典.项目(),反向=真,键=拉姆达 x: x[1])对于范围 (0, 26) 中的位置:打印字典[位置]如果位置 != len(dictionary) - 1:如果字典[位置 + 1][1] <字典[位置][1]:休息find_max_letter_count("helloworld")
输出:
<预><代码>>>>('l', 3)更新示例:
find_max_letter_count("气球")>>>('l', 2)('o', 2)
有很多方法可以缩短此过程.例如,您可以使用 Counter
类(在 Python 2.7 或更高版本中):
导入集合s = "你好世界"打印(集合.计数器(s).most_common(1)[0])
如果没有,您可以手动进行计数(2.5 或更高版本具有 defaultdict
):
d = collections.defaultdict(int)对于 c in s:d[c] += 1打印(排序(d.items(),key=lambda x:x[1],reverse=True)[0])
话虽如此,您的实施并没有什么大错.
I found this programming problem while looking at a job posting on SO. I thought it was pretty interesting and as a beginner Python programmer I attempted to tackle it. However I feel my solution is quite...messy...can anyone make any suggestions to optimize it or make it cleaner? I know it's pretty trivial, but I had fun writing it. Note: Python 2.6
The problem:
Write pseudo-code (or actual code) for a function that takes in a string and returns the letter that appears the most in that string.
My attempt:
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")
Output:
>>>
('l', 3)
Updated example:
find_max_letter_count("balloon")
>>>
('l', 2)
('o', 2)
There are many ways to do this shorter. For example, you can use the Counter
class (in Python 2.7 or later):
import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])
If you don't have that, you can do the tally manually (2.5 or later has defaultdict
):
d = collections.defaultdict(int)
for c in s:
d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])
Having said that, there's nothing too terribly wrong with your implementation.
这篇关于查找字符串中出现频率最高的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!