1
votes

I am looking for an effective way to check if a short string is in a long string. I saw some suggestions on this thread: Python efficient way to check if very large string contains a substring

However, I didn't see the use of find() there. Is it expensive to use find() function? What is the time complexity?

I've looked at the Wiki page but didn't find find() there. https://wiki.python.org/moin/TimeComplexity

1

1 Answers

4
votes

Quickly perusing the source, it appears that str.find calls stringlib_find_slice from here which eventually calls fastsearch. The actual algorithm is explained here -- with python pseudo-code (which I gleaned from reading the comments).

It looks like the implementation is in worst case O(N*M) (The same as a naive approach), but can do O(N/M) in some cases (where N and M are the lengths of the string and substring respectively), and O(N) in frequent cases1.

1(don't quote me on it -- I only skimmed the document)