python - 内置 python 函数的时间/空间复杂度

标签 python function time-complexity built-in space-complexity

split/strip/open(内置python函数)的时间/空间复杂度是多少?

有谁知道我在哪里可以查看这些函数的时间/空间复杂度?

最佳答案

确切的答案将取决于输入函数的属性。找出答案的最简单方法可能是检查这些函数的源代码。 The python source code can be found here.

让我们看看 split. 的来源代码根据属性运行不同的循环。这是按空格分割的循环。

    while (maxcount-- > 0) {
    while (i < str_len && STRINGLIB_ISSPACE(str[i]))
        i++;
    if (i == str_len) break;
    j = i; i++;
    while (i < str_len && !STRINGLIB_ISSPACE(str[i]))
        i++;

在这段代码中,函数将查看字符串中的每个字符(除非达到最大计数)。对于大小为 n 的字符串,最里面的循环将运行 n 次。时间复杂度为 O(n)

The source for strip遍历字符串中的每个字符。

    i = 0;
if (striptype != RIGHTSTRIP) {
    while (i < len) {
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
        if (!BLOOM(sepmask, ch))
            break;
        if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
            break;
        i++;
    }
}

j = len;
if (striptype != LEFTSTRIP) {
    j--;
    while (j >= i) {
        Py_UCS4 ch = PyUnicode_READ(kind, data, j);
        if (!BLOOM(sepmask, ch))
            break;
        if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
            break;
        j--;
    }

    j++;
}

这使 strip 的时间复杂度为 O(n)

The Source for open() shows no loops.这是我们所期望的。没有什么可以循环的。

关于python - 内置 python 函数的时间/空间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113713/

相关文章:

algorithm - 汉诺塔的复杂度等级

python - 将图像加载到 Dask Dataframe 中

c++ - 我的静态函数的 header 和 .cpp 发生了什么?仅在 header 中定义时运行

function - matlab中find函数的意外结果

android - 如何在键盘上的xml中为功能键设置不同的背景?

algorithm - 指数的时间复杂度

c - 提高我实现计数排序的时间复杂度(C)

jquery - 通过 jQuery 使字段只读

python - py.test setup_class 中的 tmpdir

python - 为什么 Julia 不能超集 python?