Python: 出现次数最多的字符计数器

Python: Most frequent character counter

我正在尝试创建一个程序,要求用户输入一个字符串,然后显示该字符串中出现频率最高的字符。我无法使用字典等内置功能。我认为我现在的问题是我有一个无限循环。我怎样才能解决这个问题?这是我的代码:

string = input('Enter a string:')

#space for most popular character
pop_char = ''
#initialize number of times character appears
num = 0
#initialize index
index = 0

# pick one character at a time
for ch in string:
    #initialize character counter
    cc=0

#go through entire string and compare the character to the string characters
    while index < len(string):

        #if they are the same (converted to lower case), tally one to cc
        if ch.lower() == string[index].lower():
            cc = cc + 1
            index = index + 1

        #if count is greater than or equal to previous count, use this for
        #popular character
        if cc >= num:
            num = cc
            pop_char = ch

        else:
            index = index + 1
print('The most frequently occuring letter(s):', pop_char)

if cc >= num: 应该是 if cc > num:

在您的第一次迭代中,第一个字母将等于字符串的第一个字母(显然),您将输入 if ch.lower() == string[index].lower():。这会将 cc 设置为 1,进而将 num 设置为 1

因为它们是相等的,只要第二个字母和第一个不一样,你就会有一个只进入if cc >= num部分并且永远不会更新index过去的无限循环1.

我认为您的问题是您在两个单独的 if 子句中更改索引值,并且您使用 >= 而不是 > 来检查频繁出现的字符.

想象一下循环中第一个字母 运行ning。在第一次通过时,它会将它与自身进行比较并增加索引和 cc。然后 cc 更新为 1num 更新为 1。在下一个 运行 通过时,你的字母与第二个字母不匹配,但它确实通过了第二个 if 案例,保证 none 你的值改变并且你的 index 不递增。我建议将 cc >= num 更改为 cc > num.

如果您根本无法使用任何方法,只需使用双循环即可:

def most_common():
    s = input('Enter a string:').lower()
    coun = 0
    best = ""
    for ch in s:
        cn = 0
        for c in s:
            cn += ch == c # will be True or False 1/0
        if cn >= coun: 
            if cn == coun: # catch letters that have equal count
                if ch in best: # avoid adding same char twice
                    continue
                best += ch # id equal and not already added concat to the stirng
            else:
                best = ch # else just set best
            coun = cn
    return 'The most frequently occuring letter(s): {}'.format(best)

这适用于计数相等的字符:

In [14]: most_common()
Enter a string:foobar
Out[14]: 'The most frequently occuring letter(s): o'

In [15]: most_common()
Enter a string:foobb
Out[15]: 'The most frequently occuring letter(s): ob'