整数数组中不相等元素的最小差值

0 投票
1 回答
1688 浏览
提问于 2025-04-17 17:50

我有一个包含整数数组的列表,每个元素的值都小于等于100。我需要找出每个数组中不相等的元素之间的最小差值。到目前为止,我有以下的做法(item代表一个数组):

unq  = numpy.unique(item)
mind = numpy.amin(
        (numpy.append(unq, [999]))
       -(numpy.append([-999],unq))
       )

我使用numpy,首先得到一个排序后的唯一元素数组。然后在数组的末尾加上一个很大的正数,在开头加上一个很大的负数,接着我把这两个数组相减,最后得到最小值。

有没有更快的方法来做到这一点呢?

1 个回答

1

我觉得你的解决方案还不错,不过与其使用 numpy.append,不如用 np.diff,比如可以这样写 np.diff(np.unique(a))

In [1]: import numpy as np

In [2]: a = np.random.randint(0,100,size=50)

In [4]: np.unique(a)
Out[4]: 
array([ 0,  2,  3,  5,  7,  8, 15, 18, 20, 22, 23, 27, 30, 31, 32, 33, 37,
       38, 42, 43, 45, 48, 49, 57, 59, 62, 65, 70, 74, 75, 76, 78, 79, 80,
       83, 84, 88, 91, 93, 94, 96, 98])

In [5]: np.diff(np.unique(a))
Out[5]: 
array([2, 1, 2, 2, 1, 7, 3, 2, 2, 1, 4, 3, 1, 1, 1, 4, 1, 4, 1, 2, 3, 1, 8,
       2, 3, 3, 5, 4, 1, 1, 2, 1, 1, 3, 1, 4, 3, 2, 1, 2, 2])

In [6]: np.diff(np.unique(a)).min()
Out[6]: 1

撰写回答