检查单词中最频繁出现的字母。蟒蛇

时间:2018-11-06 15:33:03

标签: python string if-statement conditional-statements

我的任务是:

编写一个将字符串作为参数并返回其中最大出现的字母的函数。

示例1:

s = 'Astana'

输出:

a

示例2:

s = 'Kaskelen'

输出:

ke

到目前为止,我已经有了这个code(点击运行):

a = input()


def most_used(w):

    a = list(w)
    indexes = []
    g_count_max = a.count(a[0])

    for letter in a:
        count = 0
        i = int()
        for index in range(len(a)):
            if letter == a[index] or letter == a[index].upper():
                count += 1
                i = index
        if g_count_max <= count:       //here is the problem.
            g_count_max = count
            if i not in indexes:
                indexes.append(i)


    letters = str()

    for i in indexes:
        letters = letters + a[i].lower()

    return letters

print(most_used(a))

问题在于它会自动将第一个字母添加到数组中,因为第一个元素的外观总和实际上等于外观的起始点(基本上是第一个元素)。

示例1:

s = 'hheee'

输出:

he

示例2:

s = 'malaysia'

输出:

ma

4 个答案:

答案 0 :(得分:4)

我认为您可以通过使用标准库的Counter对象来简化您的操作

from collections import Counter
def most_used(word):
    # this has the form [(letter, count), ...] ordered from most to least common
    most_common = Counter(word.lower()).most_common()
    result = []
    for letter, count in most_common:
        if count == most_common[0][1]:
            result.append(letter) # if equal largest -- add to result
        else:
            break  # otherwise don't bother looping over the whole thing
    return result  # or ''.join(result) to return a string

答案 1 :(得分:2)

您可以将字典理解与列表理解和max()结合使用:

s = 'Kaskelen'

s_lower = s.lower() #convert string to lowercase

counts = {i: s_lower.count(i) for i in s_lower}

max_counts = max(counts.values()) #maximum count

most_common = ''.join(k for k,v in counts.items() if v == max_counts)

收益:

'ke'

答案 2 :(得分:0)

使用列表推导功能尝试以下代码:

word = input('word=').lower()
letters = set(list(word))
max_w = max([word.count(item) for item in letters])
out = ''.join([item for item in letters if word.count(item)==max_w])
print(out)

答案 3 :(得分:-1)

还可以导入Counter lib:

public class ManagerService {

    public static void main(String[] args) {
        try {
            FactoryHelper factoryHelper = new FactoryHelper();
            Properties prop = factoryHelper.getPropFile();
            String toShorten = prop.getProperty("defaultUrl");
            ConnectAndBrowse connectAndBrowse = new ConnectAndBrowse(toShorten);
            WebDriver driver=connectAndBrowse.browseToUrlWithShortLink();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

然后返回:

from collections import Counter

a = "dagsdvwdsbd"

print(Counter(a).most_common(3)[0][0])