Python 3.3中最常见的字符

时间:2017-11-12 21:35:49

标签: python python-3.x count range character

此程序允许用户输入字符串并显示字符串中最常出现的字符。 我需要帮助解释频繁= i

# This program displays the character that appears most frequently in the string

def main():

    # Local variables.
    count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    index = 0
    frequent = 0

    # Get input.
    user_string = input('Enter a string: ')
    for ch in user_string:
        ch = ch.upper()

        # Determine which letter this character is.
        index = letters.find(ch)
        if index >= 0:

            # Increase counting array for this letter.
            count[index] = count[index] + 1

    # Please help me explain this entire part!
    for i in range(len(count)):
        if count[i] > count[frequent]:
            frequent = i

    print('The character that appears most frequently' \
          ' in the string is ', letters[frequent], '.', \
          sep='')


# Call main
main()

2 个答案:

答案 0 :(得分:0)

有问题的代码段:

for i in range(len(count)):
    if count[i] > count[frequent]:
        frequent = i

首先,for循环遍历count的长度,即26。

if语句:

if count[i] > count[frequent]:

检查for循环中的当前字母是否大于当前最常用的字符。如果是,那么它将新的最常用字符设置为for循环的索引。

例如,

如果A被引用12次而B被引用为14,那么当i = 1时,if语句将如下所示:

if 12 > 14:
   frequent = 1

这会将频率设置为1,可用于查找ex的计数频率。 count [1] == 14

答案 1 :(得分:0)

列表count中有26个不同的项目,字符集中有26个字母。它遍历每个项目的count列表(即for i in range (len(count))部分),然后查看该项目的值是否大于当前最大项目的值。 s found - 简单地说它找到了数组中的最大值,但是frequent = i不是获取它获得索引的值,而是设置当前找到的最大值的索引,因为它迭代到变量{{1} }。简单地说,它更简单,更蟒蛇     频率=指数(最大值(计数) 它具有完全相同的效果