Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all elements of one array is in another array

Tags:

python

list

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?

like image 652
iam_agf Avatar asked Dec 26 '13 18:12

iam_agf


2 Answers

issubset should help you

set(B).issubset(set(A))

e.g.:

>>> A= [1,2,3,4]
>>> B= [2,3]
>>> set(B).issubset(set(A))
True

edit: wrong, this solution does not imply the order of the elements!

like image 132
LPH Avatar answered Nov 09 '22 06:11

LPH


How about this:

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

B = [4,5,6,7]
C = [7,8,9,0]
D = [4,6,7,5]

def is_slice_in_list(s,l):
    len_s = len(s) #so we don't recompute length of s on every iteration
    return any(s == l[i:len_s+i] for i in xrange(len(l) - len_s+1))

Result:

>>> is_slice_in_list(B,A)
True
>>> is_slice_in_list(C,A)
True
>>> is_slice_in_list(D,A)
False
like image 34
Akavall Avatar answered Nov 09 '22 05:11

Akavall