python - 如何在python中找到内置函数的复杂性

标签 python algorithm time-complexity

我有问题的特例,但很高兴知道是否可以实现任何功能。

所以我想找到一个子串在字符串中的位置。好的,在 python 中有一个 find method这正是需要的。

string.find(s, sub[, start[, end]])

Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

太神奇了,但问题是在一个大字符串中找到一个大子字符串可以从 O(n*m) 运行到 O(n)(这是一个大笔交易)depending on the algorithm .文档没有提供有关时间复杂度的信息,也没有提供有关底层算法的信息。

我看到很少有方法可以解决这个问题:

  • 基准
  • 查看源代码并尝试理解它

两者听起来都不太容易(我希望有更简单的方法)。那么我怎样才能找到内置函数的复杂性呢?

最佳答案

您说,“转到源代码并尝试理解它”,但这可能比您想象的要容易。一旦你得到实际的实现代码,在Objects/stringlib/fastsearch.h ,你会发现:

/* fast search/count implementation, based on a mix between boyer-
   moore and horspool, with a few more bells and whistles on the top.
   for some more background, see: http://effbot.org/zone/stringlib.htm */

URL referenced there对算法及其复杂性进行了很好的讨论。

关于python - 如何在python中找到内置函数的复杂性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26561845/

相关文章:

不存在的行上的python3-无效语法

php - 重新排序具有排名的多个项目的算法

algorithm - 在 O(1) 中构建二叉树?

algorithm - 选择排序递归关系

python - 如何从单个列表返回 2 个单独的列表?

python - 在 Python 中打包旧版 Fortran。可以使用 setuptools 和 numpy.distutils 吗?

java - 用Java递归求和整数

c# - 查找相关提交的高效算法

java - Collection.toArray() 的时间复杂度是多少?

Python 创建一个线程并在按下按键时启动它