最常见的角色问题 - Python?

时间:2017-10-23 18:14:29

标签: python

我正在尝试编写一个程序,让用户输入一个字符串,并显示输入的字符串和字符串中最常出现的字符。该程序可以处理大小写字符相同。如果存在平局,则应输出两个字符。使用以下字符串测试程序:

The House on Haunted Hill
Python programming is fun
Gone with the Wind

该程序仅适用于" Python编程很有趣"但是我只得到另一个字符的频率,而不是字母。

def main():

    string = input('Enter a sentence: ')

    string.lower()

    counter = 0
    total_counter = 0

    most_frequent_character = ""

    for ch in string:
        for str in string:
            if str == ch:

                counter += 1
        if counter > total_counter:
            total_counter = counter
            most_frequent_character = ch
        counter = 0

    print("The most frequent character is", most_frequent_character, "and it appears", total_counter, "times.")

main()

5 个答案:

答案 0 :(得分:0)

在从用户那里获得输入后尝试使用这两行。

1,0,3,0,2
0,2,1,0,3
ETC

你需要小写所有字符,然后去掉空格(假设你没有将空格作为一个字符)。

答案 1 :(得分:0)

实际上,你 获得最频繁的角色。你在输入中留下空格;空间往往是最常见的角色。请注意输出:

The most frequent character is   and it appears 4 times.
                               ^

看到那里的额外空间?中间的一个是你最常见的角色。

尝试更改输入转换行以删除空格:

string = string.replace(' ', '').lower

现在,输出是

> Enter a sentence: The House on Haunted Hill
The most frequent character is h and it appears 4 times.
> Enter a sentence: Python programming is fun
The most frequent character is n and it appears 3 times.

答案 2 :(得分:0)

  

如果有平局,则应输出两个字符。

如果有多个字母具有相同的最大频率,则可以使用列表来存储这些字母。

from collections import Counter
s = "Hello SO!"
c = Counter(list(s.replace(' ','').lower()))
max_freq = max(c.values())
letters = [letter for letter in c if c[letter] == max_freq]

msg = 'Most frequent character is {} and it appears {} times.'
print(msg.format(','.join(letters), max_freq))
# Most frequent character is l,o and it appears 2 times.

答案 3 :(得分:0)

rand() % (N - i) < m

对于a-z中的所有字符,alph数组初始化为0。

  

ord(c) - ord('a')

计算需要递增的alph索引

答案 4 :(得分:0)

你没有得到第一个字母是因为空格被认为是频率最高的字符。为了摆脱空间,你可以试试我在这里编辑的。只需添加一个命令行即可在计算空间时传递。我将lower()放在第一行以使其正常工作。

def main():

    string = input('Enter a sentence: ').lower()

    counter = 0
    total_counter = 0

    most_frequent_character = ""

    for ch in string:
        if ch == ' ':
            pass
        else:
            for str in string:
                if str == ch:
                    counter += 1
            if counter > total_counter:
                total_counter = counter
                most_frequent_character = ch
            counter = 0
    print("The most frequent character is", most_frequent_character, "and it appears", total_counter, "times.")

main()
output:
Enter a sentence: The House on Haunted Hill
The most frequent character is h and it appears 4 times.