No. of occurrences of maximum item in a list

Question:

Suppose I have a list

L= [3 2 1 3 5 4 5 3 5 3]

Output should be 3 as 5 is maximum in the list as its no. of occurrences is 3

I am able to try this till now

from collections import defaultdict

d = defaultdict(int)
for i in height:
    d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print len(result)

But this is not working for every list as it is only giving maximum occurrences of a item in a list but sometimes it is not maximum item.

Asked By: Pankaj Sharma

||

Answers:

Check this Code:-

L= [3, 2, 1, 3, 5, 4, 5, 3, 5, 3]
newDict = {}
for i in L:
   newDict.setdefault(i,0)
   newDict[i]+=1

 filter( lambda x : (newDict[x] == max(newDict.values())) ,newDict)[0]
Answered By: Rakesh Kumar

You were picking the maximum count, rather than the maximum item. You could have solved this by dropping the key argument to max(), and then just print the result (not the length of it, that’ll always be 2!):

result = max(d.iteritems())
print result  # prints the (maxvalue, count) pair.

Alternatively, print result[1] to just print the count for the maximum value.

Use a collections.Counter() object to count your items, then find the maximum key-value pair in that:

from collections import Counter

counts = Counter(L)
max_key, max_key_count = max(counts.iteritems())
print max_key_count

Like your own, this is a O(KN) approach where K is the length of L and N is the number of unique items. This is slightly more efficient than the max_element = max(L); count = L.count(max_element) approach in that it avoids looping over all of L twice. Which one is faster in practice depends on how much smaller N is to K.

Answered By: Martijn Pieters

Use max and list.count:

max_element= max(L)
count= L.count(max_element)
print(count)
Answered By: Aran-Fey

you can use numpy as a short solution

import numpy as np
l = np.array([1,3,3,3,1,3,4,5])
x = np.bincount(l).argmax()
print(x)

result => 3

Answered By: hamza mon
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.