In python, it's very easy to get the count of a particular item in a list:
>>> L = [1,1,1,2,3,4]
>>> print(L.count(1))
3
Is this method O(N)? Is it advisable to use this method, or are there better ways of quickly getting the count of an arbitrary number of elements in a list (i.e. a way to avoid O(mN), where m is the number of records for which a call to count is required).
Yes, use collections.Counter if you need to count more than one time through the iterable. Then you will only have to iterate once.
>>> from collections import Counter
>>> counter = Counter('hellooo i am a potato!!!!!')
>>> counter.most_common(2)
[('o', 5), ('!', 5)]
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