class MyString:
def __init__(self, myString):
self.__myString = myString
def countWord(self):
count = len(self.__myString.split())
return count
def findMostFrequentChar(self):
# ?
我需要实现findMostFrequenctChar
。她给我们的唯一暗示是我们需要列两张单子。这就是她失去我的地方。在
以下是调用函数的代码:
^{pr2}$
Tags:
我会用口述来存储计数。 但是首先我要去掉所有的
spaces
和其他符号,然后是a-z,我还想把大写字母和小写字母计数为一个相同的数字。在当dict用我的所有值构造时,我使用
max
函数。max
接受iterable,因此我们将dict作为元组(key, val)
的“list”传递。我们需要告诉max
如何确定要比较的内容,因为我们给了一个lambda函数,它将元组中的第二个元素(val
)转换为key-arg
。在作为回报,max将抛出具有最高
val
的元组。在这似乎意味着你不能使用
collections.Counter
, 可能连字典都没有。在如果我们可以假设字母被定义为英文字母, 一张单子就够了。 在这种情况下,可以创建一个包含26个项的列表,所有项都初始化为0。 然后你可以迭代字符串的字符, 对于英语字母表中的每个字母,递增列表中第
n
-项的计数,其中n
是字母表中字母的索引。在创建26个零的列表:
循环输入字符串
^{pr2}$s
的字符:检查字符是否为字母:
计算字母表中字母的从0开始的索引,并递增计数:
一旦你知道了, 您可以找到具有最大值的索引(作为练习留给您), 并用
chr(index + ord('a'))
得到相应的字符。在您可以使用
sorted
:相关问题 更多 >
编程相关推荐