-1

I want to know if the text contain any text of the list.

I wrote the code below.

But it needs for-loop, I think it is possible to be more quickly.

Pleas tell me faster code?

subject_type_list = ['dog','cat','sheep','turtle']
searched_text = 'wertyuisdfghdog;;rtyuiobnmcatuio'

def confirm_existence():
    for search_word in subject_type_list:
        if search_word in searched_text:
            return True
    return False

confirm_existence()
hem
  • 1,012
  • 6
  • 11
  • Dear y_ito_htec, please let us know what all have you tried. There are numerous posts on internet (and on Stackoverflow as well) which tells you how to find an item in the list in various ways. In case they are not working according to you need, please specify what problem you are facing. – Sukhi Jun 28 '19 at 04:19
  • 1
    Possible duplicate of [Check if multiple strings exist in another string](https://stackoverflow.com/questions/3389574/check-if-multiple-strings-exist-in-another-string) – Chris Jun 28 '19 at 04:25
  • @Taegyung did you mean a [DFA](https://en.m.wikipedia.org/wiki/Deterministic_finite_automaton) ? KMP is implemented as a DFA but is specified for a single string searched. – Michael Doubez Jun 28 '19 at 04:30
  • @MichaelDoubez No, I did mean KMP, but after looking up the implementation, it seems that the built-in string search is a variation of Boyer-Moore, so using KMP won't help much. – Ignatius Jun 28 '19 at 04:43
  • Have you tried using regex? – Henry Yik Jun 28 '19 at 06:24
  • @Henry Yik No I haven't. – pythago418 Jun 28 '19 at 07:58

2 Answers2

0

Your code is fine, and I'd say it's the normal way to solve the problem. If you're looking for something more concise, you can rewrite your function using any:

subject_type_list = ['dog','cat','sheep','turtle']
searched_text = 'wertyuisdfghdog;;rtyuiobnmcatuio'

def confirm_existence():
    return any(x in searched_text for x in subject_type_list)

print( confirm_existence() ) # True

Or just use any outright:

subject_type_list = ['dog','cat','sheep','turtle']
searched_text = 'wertyuisdfghdog;;rtyuiobnmcatuio'

print( any(x in searched_text for x in subject_type_list) ) # true
Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
0

You can discard the for loop by using regular expressions. There is an excellent manual here.

Whether this will be faster depends mostly on the number of search patterns and the length of the string. If you have a large number of search patterns and/or long search strings, a solution with regular expressions will be faster. Something like this should do the trick.

import re

subject_type_list = ["dog", "cat", "sheep", "turtle"]
searched_text = "wertyuisdfghdog;;rtyuiobnmcatuio"

pattern = re.compile(r"|".join(subject_type_list))
matches = pattern.find(searched_text)
Hans Then
  • 10,935
  • 3
  • 32
  • 51