创建一个函数,由于某种原因它被卡在循环中

时间:2014-05-02 13:58:24

标签: python python-3.x

所以我正在编写一个非常基本的函数,它接受一个字符串并返回列表中最常见的字符。由于某种原因,它陷入了循环。这是代码:

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

1 个答案:

答案 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}}?),空白和标点符号。