gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:50:57 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com