2014-05-02 47 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'?),空格和標點符號。