【问题标题】:Most frequent character in Python 3.3Python 3.3 中最常见的字符
【发布时间】:2017-11-12 21:35:48
【问题描述】:

这个程序让用户输入一个字符串并显示字符串中出现频率最高的字符。 我需要帮助解释 frequent = 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()

【问题讨论】:

  • frequent = i 记住在count 列表中看到的最高计数的索引。

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


【解决方案1】:

有问题的代码sn-p:

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,可用于在计数中查找频率,例如。 计数[1] == 14

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-11-04
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 2023-04-04
      • 2012-12-08
      • 1970-01-01
      相关资源
      最近更新 更多