how to find how many times the highest number in a list appeared using python?

Viewed 205

e.g. if a list is: list = [1, 2, 3, 4, 4] how to count the amount of times number 4 appeared, while not specifying it. using max(list) or something like that.

4 Answers

Try this using max:

l = [1,2,3,4,4]
num = max(l, key=lambda x:l.count(x))  # num will be 4

the you can get the count of num.

l.count(num)  # this wil returns 2

in the other hand as @buddemat said(Here), it is better to:

from collections import Counter      
                                                                                                                                                                                                                                         
l = [1,2,3,4,4]
c = Counter(l)  
c.most_common()[0]

will give you

(4,2) # 4 is a maximum number and 2 is number of occurrence.

Also note that:

DO NOT use list as a variable name, list is predefined in python and you will override its own functionality.

While straightforward solution is to first find the maximum and then count it, here is how you can do both in one pass:

import functools
list = [1, 2, 3, 4, 4]
(max, count) = functools.reduce (
  lambda x, y:
    (y, 1) if x [0] is None or x [0] < y
    else x if x [0] > y
    else (x [0], x [1] + 1),
  list,
  (None, 0))
print (max, count)

This solution returns None, 0 for empty list.

def get_max_occ(l):    
    max_i = None
    for i in l:
        if max_i is not None:
            if i > max_i:
                max_i = i
                occ = 1
            else:
                occ += 1
        else:
            max_i = i
            occ = 1
    return occ

First, find the maximum and use count

l1 =  [1, 2, 3, 4, 4] 
maximum = max(l1)
count = l1.count(maximum)

You can replace the maximum function by yourself. If you don't like to use the built-in function by following the ways

def max(l1):
  maximum = l1[0]
  for el in l1:
   if maximum< el:
     maximum = el
  return maximum

The above function will check each element of the list iteratively.

def maximum(l1):
    if len(l1)  == 1:
        return l1[0]
    if len(l1) == 2:
        if l1[0]> l1[1]:
            return l1[0]
        else:
            return l1[1]
    
    else:
        
        max1 = maximum(l1[:len(l1)//2])
        max2 = maximum(l1[len(l1)//2:])
        if max1 > max2:
            return max1
        else:
            return max2

The above function is using the divide and conquer approach to find the maximum which time complexity is logn

Related