【问题标题】:python str.index time complexitypython str.index时间复杂度
【发布时间】:2016-08-20 11:47:31
【问题描述】:

为了在字符串中查找子字符串的位置,一个简单的算法将花费O(n^2) 时间。但是,使用一些高效的算法(例如KMP algorithm),这可以在 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()

但是,如果我们这样做:'saurabh'.index('ra'),它是在内部使用一些有效的算法在O(n) 中计算它还是使用复杂的简单算法O(n^2)

【问题讨论】:

  • 你可以分析它,看看时间是指数增长还是线性增长;)

标签: python algorithm time-complexity string-algorithm


【解决方案1】:

在那篇文章 [1] 中,作者通过算法并对其进行了解释。来自文章:

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

并且来自 Boyer–Moore–Horspool 算法 [2] 的 wiki 页面:

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.

希望有帮助!

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

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

【讨论】:

  • 但是 KMP 的最坏情况时间仍然是线性的。这是否意味着我们应该使用 KMP 算法而不是 python 的内置 index() 来实现我们的代码以用于时间关键的过程?
  • 我认为该线程对该主题有一个很好的答案:programmers.stackexchange.com/questions/183725/…
【解决方案2】:

【讨论】:

    【解决方案3】:

    有时你可以通过尝试得到一个快速的答案

    >>> 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2016-02-13
      • 2012-08-14
      • 2020-03-25
      相关资源
      最近更新 更多