Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return values from a list where difference != 2

I have a list e.g. my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43]

I want a function that will return all values from the list where the difference between that value and previous value is not equal to 2, e.g. the function will return [1, 14, 22, 28, 41] for the above list. Note that the first value of my_list will always appear as the first value of the output. The input lists are of non-zero length and up to the order of 100's.

So far I have this:

def get_output(array):
    start = [array[0]]
    for i in range(1, len(array)-1):
        if (array[i] - array[i-1]) != 2:
            start.append(array[i])

    return start

Is there a vectorised solution that would be faster, bearing in mind I will be applying this function to thousands of input arrays?

like image 369
Imran Avatar asked Mar 04 '26 00:03

Imran


2 Answers

To avoid using the inefficient np.concat, use np.ediff1 instead of np.diff, which takes a to_begin argument to pre-pend to the result:

>>> my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43]
>>> arr = np.array(my_list)
>>> np.ediff1d(arr, to_begin=0)
array([0, 2, 2, 2, 7, 2, 2, 4, 6, 2, 2, 9, 2])

So now, using boolean-indexing:

>>> arr[np.ediff1d(arr, to_begin=0) != 2]
array([ 1, 14, 22, 28, 41])
like image 123
juanpa.arrivillaga Avatar answered Mar 06 '26 12:03

juanpa.arrivillaga


Apart from the first element which you can add manually (although it doesn't really make sense as per Azat Ibrakov comment) you can use np.where

a = np.array([1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43])
a[np.where(a[1:] - a[:-1] != 2)[0] + 1]

array([14, 22, 28, 41])

Adding first element:

[a[0]] + list(a[np.where(a[1:] - a[:-1] != 2)[0] + 1])

[1, 14, 22, 28, 41]
like image 29
Julien Avatar answered Mar 06 '26 13:03

Julien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!