Check if all elements of one array is in another array

Viewed 38176

I have these two arrays:

A = [1,2,3,4,5,6,7,8,9,0] 

And:

B = [4,5,6,7]

Is there a way to check if B is a sublist in A with the same exact order of items?

8 Answers

You can use scipy.linalg.hankel to create all the sub-arrays in one line and then check if your array is in there. A quick example is as follows:

from scipy import linalg

A = [1,2,3,4,5,6,7,8,9,0] 

B = [4,5,6,7]

hankel_mat = linalg.hankel(A, A[::-1][:len(B)])[:-1*len(B)+1]  # Creating a matrix with a shift of 1 between rows, with len(B) columns

B in hankel_mat  # Should return True if B exists in the same order inside A 

This will not work if B is longer than A, but in that case I believe there is no point in checking :)

import array

def Check_array(c):
    count = 0
    count2 = 0  

    a = array.array('i',[4, 11, 20, -4, -3, 11, 3, 0, 50]);
    b = array.array('i', [20, -3, 0]);
    
    for i in range(0,len(b)):
        
        for j in range(count2,len(a)):
            if a[j]==b[i]:
                    count = count + 1
                    count2 = j
                    break           
    if count == len(b): 
        return bool (True);
    else:
        return bool (False);

res = Check_array(8)
print(res)

By subverting your list to string, you can easily verify if the string "4567" is in the string "1234567890".

stringA = ''.join([str(_) for _ in A])
stringB = ''.join([str(_) for _ in B])

stringB in stringA 
>>> True

Dressed as a one line (cause is cooler)

isBinA = ''.join([str(_) for _ in B]) in ''.join([str(_) for _ in A])
isBinA 
>>> True
Related