-1

I have two lists such as:

A=[1,2,3,4]
B=[3,6,7,8,9,10]

I want to compare these two list and if there is at least one element in common it return True otherwise False. Currently I am using the following:

Set(A)&Set(B)

However this is not the most efficient way for this purpose. I have more than 2 million sets with more than 10K elements in each that need to be compared. I really do not need to compare all elements.

Is there any build-in function for it in Python or do I need to write a custom function for it?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Amir
  • 1,017
  • 4
  • 14
  • 32
  • The same problem is already discussed in this question: https://stackoverflow.com/questions/3170055/test-if-lists-share-any-items-in-python – Nadni Dec 30 '17 at 16:34

2 Answers2

0

You can concatenate the lists, cast to set, and check for existence:

A=[1,2,3,4]
B=[3,6,7,8,9,10]
def check_existence(a, b):
   return bool([i for i in set(a+b) if i in set(a) and i in set(b)]
print(check_existence(A, B))
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

I think the key point is you need to improve your data structure to store the data when fetching or receiving them.

For example, use a dict to store them, key = the number in your array, the value presents A, B or (A and B), A = 1, B = 2 , A and B = 3.

Then you can find check if there is any value = 3, you can return True.

If you can keep order of the value, that will be great, because you only get the biggest value, if it is 3, then return True, that is O(1).

Rong Zhao
  • 318
  • 1
  • 16