Pankaj Sharma
Pankaj Sharma

Reputation: 388

No. of occurrences of maximum item in a list

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.

Upvotes: 1

Views: 6210

Answers (4)

hamza mon
hamza mon

Reputation: 97

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

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124538

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.

Upvotes: 3

Rakesh Kumar
Rakesh Kumar

Reputation: 4420

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]

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43296

Use max and list.count:

max_element= max(L)
count= L.count(max_element)
print(count)

Upvotes: 6

Related Questions