2013-12-15 21 views
7

這是我到目前爲止有:計數occurence

alist=[1,1,1,2,2,3,4,2,2,3,2,2,1] 
def icount(alist): 
    adic={} 
    for i in alist: 
     adic[i]=alist.count(i) 
    return adic 

print(icount(alist)) 

我做了一些研究,以找出list.count()的時間複雜度爲O (n),因此,這個代碼將是O(n^2)。

有沒有辦法將它減少到O(nlogn)?

+0

參見['collections.Counter'(HTTP://文檔.python.org/3 /庫/ collections.html#collections.Counter)。正是這種工作。 – falsetru

+0

如果你只增加'adic [i]',複雜度應該是O(n)。 – Barmar

+0

但我怎麼知道它的時間複雜度? –

回答

11

您可以使用Counter這樣

from collections import Counter 
alist=[1,1,1,2,2,3,4,2,2,3,2,2,1] 
print Counter(alist) 

如果你想使用你的解決方案,可以提高它像這樣

def icount(alist): 
    adic = {} 
    for i in alist: 
     adic[i] = adic.get(i, 0) + 1 
    return adic 

更妙的是,你可以使用defaultdict這樣

from collections import defaultdict 
adic = defaultdict(int) 
for i in alist: 
    adic[i] += 1 
return adic 

另外,你可能想看看v的時間複雜性在不同的Python arious操作對象here

+0

'get'是一個列表數據類型的函數嗎? alist.get(2,0)給我一個錯誤 –

+0

@AswinMurugesh對不起。修復。請現在檢查:) – thefourtheye

+0

你能解釋一下它到底是什麼嗎? –

6

計數器是你的幫助:

>>> from collections import Counter 
>>> a = [1,2,1,3,4] 
>>> Counter(a) 
Counter({1: 2, 2: 1, 3: 1, 4: 1}) 
>>> x = Counter(a)  
>>> x[1] 
2 
>>> x[2] 
1 

獲取每個元素的數量很容易通過這種方法