1

This is related to my earlier question: Elementwise logical comparison of numpy arrays

I have two numpy arrays of random integers

A=np.random.randint(Q,size=(N,M))
B=np.random.randint(Q,size=(1,M))

I need to test if any of the rows in A have more than 0 and less than M common elements elementwise with B.

For example if

A=np.array([[2,0],[0,1],[1,2]])
B=np.array([1,0])

I would expect True since [1,0] and [1,2] share more than 0 and less than 2 elements elemenwise.

On the other hand if

B=np.array([2,0])

I would expect False since there are only rows which chare 2 or 0 elements elementwise

At the moment my approach is:

c=np.where((A[:]==B))[0]
n=np.bincount(c)
((n==0)+(n==2)).all()

To me this seems like a convoluted way of testing this and I was wondering if there was a more natural way that I'm missing.

Community
  • 1
  • 1
Artturi Björk
  • 3,643
  • 6
  • 27
  • 35

1 Answers1

1

I would do it like this

neq=(A==B).sum(-1)
result = any(logical_and(neq<B.size, neq>0))

where neq keeps track of how many digits each line of A has in common with B.

gg349
  • 21,996
  • 5
  • 54
  • 64