Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurence in a list with time complexity of O(nlogn)

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)?

like image 754
D.X.D Avatar asked Dec 15 '13 06:12

D.X.D


People also ask

How do you count occurrences of an item in a list?

Use the list. count() method of the built-in list class to get the number of occurrences of an item in the given list.

What is the time complexity of count () method?

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.

Is there any count function in list?

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.

How do you count all occurrences in a list in Python?

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.


2 Answers

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

like image 190
thefourtheye Avatar answered Nov 15 '22 21:11

thefourtheye


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

like image 29
Aswin Murugesh Avatar answered Nov 15 '22 20:11

Aswin Murugesh