Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a tuple in large a very large list

Suppose I have a list of tuples:

tuple_library = [('a', 'z', '1'), ('r', '3', 'b'), ('m', '1', 'l')]

What I want to do is to check if the following tuple is present on the tuple_library.

search_list = [('a','a','1'), ('m', '1', 'l')]


def search_the_tupple(t_lib, s_list):
    for item in t_lib:
        if item in s_list:
           return(item)

print(search_the_tupple(tuple_library, search_list))

this code works ok if the tuple_library and the search_list is small, but as those two item increases, the longer time needed in order for it to complete.

How do we approach this problem?

like image 735
Led Avatar asked Jan 25 '23 10:01

Led


1 Answers

  1. Convert tuple_library and search_list to a python set with set()
  2. Return the intersection of the two sets, that is, all the elements that are in both tuple_library and search_list
tuple_library = [('a', 'z', '1'), ('r', '3', 'b'), ('m', '1', 'l')]
search_list = [('a','a','1'), ('m', '1', 'l')]


def search_the_tupple(t_lib, s_list):
    return set(t_lib).intersection(set(s_list))


print(search_the_tupple(tuple_library, search_list))

This is assuming that you want the order of the tuple to be preserved. (so that a ('m', '1', 'l') would appear but a ('m', 'l', '1') would not.

Fyi: it does not matter whether you do t_lib.intersection(s_list) or the other way around.

like image 174
SoySoy4444 Avatar answered Feb 03 '23 08:02

SoySoy4444