Home > Back-end >  Check if at least one tuple is present in a string
Check if at least one tuple is present in a string

Time:08-20

I have a list of tuple. I want to check if both the tuple elements are present in a string.

I came up with this code.

def check_if_present(user_name):
    is_present = False
    tuple_list = [('firstname1', 'secondname1'), ('firstname2', 'secondname2'), ('firstname3', 'secondname3')]
    for user, name in tuple_list:
        if user in user_name and name in user_name:
            is_present = True
    return is_present

check_if_present('firstname1 secondname2 test1') should return False and check_if_present('firstname1 secondname1 test4') should return True

How can I reduce the lines of code to achieve the same logic? Or How can I achieve it efficiently?

CodePudding user response:

You can use any() to short-circuit the search:

tuple_list = [
    ("firstname1", "secondname1"),
    ("firstname2", "secondname2"),
    ("firstname3", "secondname3"),
]


def check_if_present(user_name, tuple_list):
    return any(
        user in user_name and name in user_name for user, name in tuple_list
    )


print(check_if_present("firstname1 secondname2 test1", tuple_list))
print(check_if_present("firstname1 secondname1 test4", tuple_list))

Prints:

False
True

CodePudding user response:

Although using any() is elegant and "Pythonic", it is not the fastest solution. You can short_circuit the search also by a slight modification to your original code:

def check_if_present2(user_name, tuple_list):
    for user, name in tuple_list:
        if user in user_name and name in user_name:
            return True
    return False

This is about 2x faster than the any() version, both when the search succeeds (and is short-circuited) and when it fails (and hence is not short-circuited)

  • Related