找到最频繁的字符在字符串 [英] Finding the most frequent character in a string

查看:103
本文介绍了找到最频繁的字符在字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个规划问题,而看一个招聘启事上左右。我认为这是pretty的有趣,作为一个初学者Python程序员我试图解决它。不过,我觉得我的解决方案是相当......凌乱......任何人都可以做任何建议,以优化它或使其更清洁?我知道这是pretty的微不足道,但我很开心写它。注:Python的2.6

的问题:

写假code(或实际code)的函数,它接受一个字符串,并返回出现在最该字符串信。

我的尝试:

 输入字符串

高清find_max_letter_count(字):

    字母= string.ascii_lowercase
    词典= {}

    在字母:
        词典[来信] = 0

    在单词的字母:
        词典[来信] + = 1

    词典=排序(dictionary.items()
                        反向=真,
                        键=拉姆达X:X [1])

    有效范围内的位置(0,26):
        打印词典[位置]
        如果位置= LEN(字典) -  1!
            如果词典[位置+ 1] [1];词典[位置] [1]:
                打破

find_max_letter_count(HelloWorld的)
 

输出:

 >>>
(L,3)
 

更新例如:

  find_max_letter_count(热气球)
>>>
(L,2)
(O,2)
 

解决方案

有很多方法可以做到这一点更短。例如,您可以使用 计数器 类(在Python 2.7或更高版本):

 导入收藏
S =的HelloWorld
打印(collections.Counter(S).most_common(1)[0])
 

如果你没有,你可以做手工理货(2.5或更新版本 defaultdict ):

  D = collections.defaultdict(INT)
对于C在S:
    D [C] + = 1
打印(排序(d.items(),键=拉姆达X:X [1],反向=真)[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆