How to find the statistical mode?

前端 未结 30 2168
时光取名叫无心
时光取名叫无心 2020-11-21 07:00

In R, mean() and median() are standard functions which do what you\'d expect. mode() tells you the internal storage mode of the objec

30条回答
  •  耶瑟儿~
    2020-11-21 07:53

    Here are several ways you can do it in Theta(N) running time

    from collections import defaultdict
    
    def mode1(L):
        counts = defaultdict(int)
        for v in L:
            counts[v] += 1
        return max(counts,key=lambda x:counts[x])
    
    
    def mode2(L):
        vals = set(L)
        return max(vals,key=lambda x: L.count(x))
    
    def mode3(L):
        return max(set(L), key=lambda x: L.count(x))
    

提交回复
热议问题