Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Use max and list.count:

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

Solution 2:

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.


Solution 3:

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]

Post a Comment for "No. Of Occurrences Of Maximum Item In A List"