简体   繁体   中英

Difference in time complexity between python .index() and .find()

I was wondering what the difference in time complexity between .find() and .index() is in Python. When doing LeetCode I noticed, that the .find() method takes noticably longer then the .index() method. From my understanding both methods should run in O(n) . The only difference I see is, that .index() throws a ValueError when the element you search is not present.

Does somebody know where this speed difference comes from? And also is there a document where you can find the time complexities for various Python methods?

Both str.find and str.index are just thin wrappers around any_find_slice , and their only meaningful difference is the addition of the following in str.index :

if (result < 0) {
    PyErr_SetString(PyExc_ValueError, "substring not found");
    return NULL;
}

Thus any perceived runtime differences if true (you haven't included a benchmark that shows your claims are true) must come from the exception handling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM