Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if 2 arrays have at least one element in common?

Tags:

python

numpy

What's an easiest way to check whether or not 2 arrays have at least one element in common? Using numpy is possible, but not necessarily.

The code I've found so far only checks for the concrete common elements. Whereas I need only to check True or False condition.

like image 334
Incerteza Avatar asked Dec 14 '22 11:12

Incerteza


2 Answers

Assuming the input arrays to be A and B, you can use np.in1d with np.any, like so -

import numpy as np
np.in1d(A,B).any()

You can also use NumPy's broadcasting capability, like so -

(A.ravel()[:,None] == B.ravel()).any()
like image 58
Divakar Avatar answered Feb 11 '23 10:02

Divakar


You can use any:

any(x in set(b) for x in a)

This is short to write but, as Jon has rightly pointed out it will create a new set(b) for each element at a, the following lines would avoid that:

sb = set(b)
any(x in sb for x in a)

Performance will improve if b is the largest array (compared to a):

(smaller,bigger) = sorted([a,b], key=len)
sbigger = set(bigger)
any(x in sbigger for x in smaller)
like image 42
Pablo Francisco Pérez Hidalgo Avatar answered Feb 11 '23 11:02

Pablo Francisco Pérez Hidalgo