简体   繁体   中英

Minimum difference between non-equal elements in integer array

I do have a list with integer arrays where every element has value <= 100. I need to figure out the smallest difference between non-equal elements for every array. So far I have the following ( item represents one array):

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

Using numpy I first get sorted array of unique elements. After adding high positive number at the end and high negative number at the beginning I substract these two arrays and get minimum value.

Is there any faster way to do this?

I think your solution is ok except that instead of using numpy.append you would better use np.diff , like 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM