2014-05-02 49 views
1

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

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 
+3

改为查看['collections.Counter()'对象](https://docs.python.org/2/library/collections.html#collections.Counter);它可以开箱即用:'返回Counter(string).most_common()[0] [0]'。 –

回答

2

您的代码卡在一个循环,因为当common == "",即当while循环开始运行,string.count(common) == len(string) + 10,如你期望的那样)。因此,您永远无法找到更多常见的char s来添加到values,因此values的长度永远不会结束循环。

另外,当找到更常见的问题时,您似乎没有计划从values中删除不常用的char

正如马亭指出,这很容易用Counter实现:

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'?),空格和标点符号。