gpt4 book ai didi

python - 如何计算字符串中出现次数最多的字母?

转载 作者:太空狗 更新时间:2023-10-29 22:14:47 27 4
gpt4 key购买 nike

class MyString:
def __init__(self, myString):
self.__myString = myString

def countWord(self):
count = len(self.__myString.split())
return count

def findMostFrequentChar(self):
# ?

我需要实现 findMostFrequenctChar。她给我们的唯一提示是我们需要制作 2 个列表。这就是她失去我的地方。

调用函数的代码如下:

def main():
aString = MyString("This is a super long long long string. Please help count me")
print("There are", aString.countWord(), "words in the string.")

count, letter = aString.findMostFrequentChar()
print("The most frequent character is", letter, "which appeared", count, "times")

main()

最佳答案

The only hint she gave us was that we needed to make 2 lists. and this is where she lost me.

这似乎暗示你不能使用collections.Counter,甚至可能没有字典。

如果我们可以假设字母被定义为英文字母表,那么一个列表就足够了。在这种情况下,您可以创建一个包含 26 个项目的列表,所有项目都初始化为 0。然后你可以遍历字符串的字符,对于英文字母表中的每个字母,增加列表中第 n 项的计数,其中 n 是字母表中字母的索引。

创建一个包含 26 个零的列表:

counts = [0] * 26

循环输入字符串s的字符:

for c in s:

检查字符是否为字母:

if 'a' <= c.lower() <= 'z'

计算字母表中字母从 0 开始的索引并递增计数:

index = ord(c.lower()) - ord('a')
counts[index] += 1

一旦你有了计数,您可以找到具有最大值的索引(留给您作为练习),并用chr(index + ord('a'))获取对应的字符。

关于python - 如何计算字符串中出现次数最多的字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47251934/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com