1

我正在一个实验室(在 Python 3 中)工作,该实验室要求我在最常出现的字符串中查找并打印字符。例如:

>>> print(maxCharCount('apple'))
['p']

这个想法是使用循环来做到这一点,但我对如何做到这一点感到困惑。

4

4 回答 4

4
def maxCharCount(ss):
    return max(ss, key=ss.count)
于 2016-03-02T01:39:03.203 回答
1

因为您真的想使用 for 循环:

a = 'apple'
m = set(a)
max = 0
for i in m:
    if a.count(i) > max:
         max = a.count(i)

编辑:我没读好,你实际上想要的字母不是它出现的次数所以我把这段代码编辑成:

a = 'apple'
m = set(a)
max = 0
p = ''
for i in m:
        if a.count(i) > max:
             max = a.count(i)
             p = i
于 2016-03-02T01:38:08.490 回答
1
def max_char_count(string):
    max_char = ''
    max_count = 0
    for char in set(string):
        count = string.count(char)
        if count > max_count:
            max_count = count
            max_char = char
    return max_char

print(max_char_count('apple'))
于 2016-03-02T01:40:35.017 回答
0
def count(char, string):
    c = 0
    for s in string:
        if char == s:
            c += 1
    return c

def max_char_count(string):
    biggest = string[0]
    for c in string:
        if count(c,string) > count(biggest,string):
            biggest = c
    return biggest
于 2016-03-02T01:52:32.110 回答