MasAdam
MasAdam

Reputation: 453

Comparing Range Between Two Arrays

I have two different arrays:

A = [1,6,8]
B = [2,5,6,9]

I want to check whether there is at least one element from B exist in Range of A

Example:

Let's say I have two values X = 1 and Y = 8 from list A.

I want to check whether there is such element in list B exist within the range of X and Y.

The answer that I expected is for python to tell me that 2, 5, 6 are elements from B that fit in the range of A[0] and A[2]

I tried:

for n in range(x,y)

    if n in B 

but it didn't work.

Did I do it wrong?

Upvotes: 0

Views: 644

Answers (2)

jfs
jfs

Reputation: 414255

I want to check whether there is at least one element from B exist in Range of A

To find whether any element from B exists in A:

exists = not set(A).isdisjoint(B)

that is O(len(A) + len(B)) in time unlike exists = any(b in A for b in B) that is O(len(A) * len(B)) algorithm e.g., if A, B have one million elements each then the first method (set.isdisjoint()) requires around a million (10**6) operations while the second method (with the loop) requires around a million of millions (10**12) operations that is much too slow.


To find whether any element from B exists in range(A[0], A[2]):

exists = any(A[0] <= b < A[2] for b in B)

Upvotes: 0

Incognito
Incognito

Reputation: 3094

This is how you can do it.

list_1 = [1, 6, 8]
list_2 = [2,5,5,8]
for n in range (list_1 [0], list_1 [2]):
    if n in list_2:
        print n

Upvotes: 1

Related Questions