Check if 2 arrays have at least one common element?

What is an easy way to check if 2 arrays have at least one common element? Using numpy is possible, but not necessary.

The code I have found so far only checks for specific generic elements. While I only need to check the True or False condition.

+4
source share
4 answers

Assuming the input arrays will be Aand B, you can use np.in1dwith np.any, also -

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

You can also use NumPy broadcasting capability, for example:

(A.ravel()[:,None] == B.ravel()).any()
+3
source

You can use any:

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

, , , set(b) a, :

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

, b - ( a):

(smaller,bigger) = sorted([a,b], key=len)
sbigger = set(bigger)
any(x in sbigger for x in smaller)
+3

I would go with kits .

def doArraysIntersect(array1, array2):
    return bool(set(array1) & set(array2))
+3
source
def lists_overlap(a, b)
    for i in a:
       if i in b:
            return True
    return False
+1
source

Source: https://habr.com/ru/post/1610417/


All Articles