所以我正在编写一个非常基本的函数,它接受一个字符串并返回列表中最常见的字符。由于某种原因,它陷入了循环。这是代码:
def frequent(string, amount):
'''frequent(str) --> list
This function takes a string and returns a list of the
most frequent characters in order, without repetition.'''
values = []
common = ''
while len(values) != amount:
for char in string:
if string.count(char) > string.count(common):
common = char
values.append(char)
string = string.strip(char)
return values
答案 0 :(得分:2)
您的代码陷入循环,因为当common == ""
时,即while
循环开始运行时,string.count(common) == len(string) + 1
(不 0
,如你所料)。因此,您永远不会找到任何更常见的char
来添加到values
,因此values
永远不会长到足以结束循环。
此外,当您找到更常见的char
时,您似乎没有计划从values
中移除较不常见的Counter
。
正如Martijn指出的那样,使用from collections import Counter
def frequent(s, n):
"""Returns a list of the n most frequent characters in s."""
return [char for char, count in Counter(s).most_common(n)]
:
'a'
您可能还想考虑为大写字母和大写字符添加处理('A'
计为{{1}}?),空白和标点符号。