Time/space 内置 python 函数的复杂性

Time/space complexity of in-built python functions

split/strip/open(内置 python 函数)的 time/space 复杂度是多少?

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

确切的答案将取决于输入函数的属性。找出答案的最简单方法可能是检查这些函数的源代码。 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. 这就是我们所期望的。没有什么可以循环的。