How to make numpy.argmax return all occurrences of the maximum?

后端 未结 3 991
误落风尘
误落风尘 2020-12-03 06:30

I\'m trying to find a function that returns all occurrences of the maximum in a given list.

numpy.argmax however only returns the first occurrence that it f

3条回答
  •  执笔经年
    2020-12-03 07:11

    In case it matters, the following algorithm runs in O(n) instead of O(2n) (i.e., using np.argmax and then np.argwhere):

    def allmax(a):
        if len(a) == 0:
            return []
        all_ = [0]
        max_ = a[0]
        for i in range(1, len(a)):
            if a[i] > max_:
                all_ = [i]
                max_ = a[i]
            elif a[i] == max_:
                all_.append(i)
        return all_
    

提交回复
热议问题