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

问题描述 投票:-1回答:1

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

有谁知道我可以在哪里查看这些功能的时间/空间复杂性?

python function time-complexity built-in space-complexity
1个回答
0
投票

确切的答案取决于输入函数的属性。找出最简单的方法可能是检查这些函数的源代码。 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++;

在此代码中,函数将查看字符串中的每个字符(除非达到maxcount)。对于大小为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++;
}

这使得条带具有O(n)的时间复杂度。

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

© www.soinside.com 2019 - 2024. All rights reserved.