This is what I have so far:
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))
I did some research to find out that the time complexity of list.count() is O(n), thus , this code will be O(n^2).
Is there a way to reduce this to O(nlogn)?
Use the list. count() method of the built-in list class to get the number of occurrences of an item in the given list.
The time complexity of the count(value) method is O(n) for a list with n elements. The standard Python implementation cPython “touches” all elements in the original list to check if they are equal to the value. What is this? Thus, the time complexity is linear in the number of list elements.
In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
You can use Counter
like this
from collections import Counter
alist=[1,1,1,2,2,3,4,2,2,3,2,2,1]
print Counter(alist)
If you want to use your solution, you can improve it like this
def icount(alist):
adic = {}
for i in alist:
adic[i] = adic.get(i, 0) + 1
return adic
Even better, you can use defaultdict
like this
from collections import defaultdict
adic = defaultdict(int)
for i in alist:
adic[i] += 1
return adic
Also, You might want to look at the Time Complexity of various operations on different Python objects here
Counter is your helper:
>>> 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
Get the count of each element easily through this method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With