Incerteza
Incerteza

Reputation: 34884

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

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.

Upvotes: 4

Views: 5135

Answers (5)

Abishek H
Abishek H

Reputation: 209

In JavaScript

const findCommon = (arr1, arr2) => {

     let set = new Set(arr1)
     arr2.forEach((item) => {
         if (set.has(item)) return true
     })
     return false
}

Basically, I've done what everybody has suggested here. In case, you're looking for a JS solution...

Upvotes: 1

Aleksa Milosevic
Aleksa Milosevic

Reputation: 133

def lists_overlap(a, b):
    for i in a:
       if i in b:
            return True
    return False

Upvotes: 3

work.bin
work.bin

Reputation: 1108

I would go with sets.

def doArraysIntersect(array1, array2):
    return bool(set(array1) & set(array2))

Upvotes: 3

Divakar
Divakar

Reputation: 221504

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()

Upvotes: 3

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)

Upvotes: 3

Related Questions