简体   繁体   English

python str.index时间复杂度

[英]python str.index time complexity

For finding the position of a substring, inside a string, a naive algorithm will take O(n^2) time. 为了找到字符串内子字符串的位置,幼稚算法将花费O(n^2)时间。 However, using some efficient algorithms (eg KMP algorithm ), this can be achieved in O(n) time: 但是,使用一些有效的算法(例如KMP算法 ),可以在O(n)时间内实现:

s = 'saurabh'
w = 'au'

def get_table():
    i = 0; j = 2 
    t = []
    t.append(-1); t.append(0)
    while i < len(w):
        if w[i] == w[j-1]:
            t.append(j+1)
            j += 1
        else:
            t.append(0)
            j = 0 
        i += 1
    return t

def get_word():
    t = get_table()
    i = j = 0 
    while i+j < len(s):
        if w[j] == s[i+j]:
            if j == len(w) - 1:
                return i
            j += 1
        else:
            if t[j] > -1: 
                i = i + j - t[j]
                j = t[j]
            else:
                i += 1
    return -1

if __name__ == '__main__':
    print get_word()

However, if we do: 'saurabh'.index('ra') , does it internally uses some efficient algorithm to compute this in O(n) or it uses naive algorithm of complexity O(n^2) ? 但是,如果我们这样做: 'saurabh'.index('ra') ,它是在内部使用某种高效算法在O(n)进行计算还是使用复杂度为O(n^2)朴素算法?

In that article [1] author goes through the algoritm and explains it. 在那篇文章[1]中,作者详细介绍了算法。 From article: 来自文章:

The function “fastsearch” is called. It is a mix between 
Boyer-Moore and Horspool algorithms plus couple of neat tricks.

And from the wiki page of Boyer–Moore–Horspool algorithm [2]: 并从Boyer–Moore–Horspool算法的Wiki页面[2]:

The algorithm trades space for time in order to obtain an 
average-case complexity of O(N) on random text, although 
it has O(MN) in the worst case, where the length of the 
pattern is M and the length of the search string is N.

Hope that helps! 希望有帮助!

[1] http://www.laurentluce.com/posts/python-string-objects-implementation [1] http://www.laurentluce.com/posts/python-string-objects-implementation

[2] https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm [2] https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm

Sometimes you can get a quick answer just by trying 有时候,只要尝试一下就可以快速得到答案

>>> timeit.timeit('x.index("ra")', setup='x="a"*100+"ra"')
0.4658635418727499
>>> timeit.timeit('x.index("ra")', setup='x="a"*200+"ra"')
0.7199222409243475
>>> timeit.timeit('x.index("ra")', setup='x="a"*300+"ra"')
0.9555441829046458
>>> timeit.timeit('x.index("ra")', setup='x="a"*400+"ra"')
1.1994099491303132
>>> timeit.timeit('x.index("ra")', setup='x="a"*500+"ra"')
1.4850994427915793

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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