简体   繁体   中英

Finding consecutive and identical integer into a vector

I have vectors with 0 and 1.

a = np.array([1,1,0,0])
b = np.array([1,0,0,1])
c = np.array([0 1 1 0])
d = np.array([0 1 0 1])

I would like to implement a function checking if the 1 are consecutive in the vector by disregarding the end of the vector, ie last element wih first element. Expected results will be:

check(a) --> True
check(b) --> True
check(c) --> True
check(d) --> False

The easy solution will be to scroll through each vector. However I feel that an easier and smarter is doable with some np.diff or np.nonzero combination. Any idea?

Thanks a lot.

You could use np.roll + np.logical_and + np.count_nonzero

import numpy as np


def check(arr):
    return np.count_nonzero(np.logical_and(np.roll(arr, 1), arr)) > 0


a = np.array([1, 1, 0, 0])
b = np.array([1, 0, 0, 1])
c = np.array([0, 1, 1, 0])
d = np.array([0, 1, 0, 1])

print(check(a))
print(check(b))
print(check(c))
print(check(d))

Output

True
True
True
False

Maybe you can try something like this,

def check(k):
    return any( i in np.diff(np.where(k==1)) for i in [1, len(k)-1])

np.where(k==1) , this will return a list of indices where your vector is 1.

np.diff(np.where(k==1)) , this will evalute the difference between consequative indices where your vector is 1.

Finally any( i in np.diff(np.where(k==1)) for i in [1, len(k)-1]) this will check if there are consecutive 1's. Either if their difference is 1 or length of your vector - 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