gpt4 book ai didi

python - Python 的 strip() 的运行时间是多少?

转载 作者:太空宇宙 更新时间:2023-11-04 08:08:08 25 4
gpt4 key购买 nike

Python 的 strip() 的运行时间是多少?

既然 remove 对于单个 char 是 O(n),那么对于 string strip 是 O(n^2) 吗?

最佳答案

它也是 O(N) 而已。引用与去除空格的普通 strip 相对应的代码,from the version 2.7.9

Py_LOCAL_INLINE(PyObject *)
do_strip(PyStringObject *self, int striptype)
{
char *s = PyString_AS_STRING(self);
Py_ssize_t len = PyString_GET_SIZE(self), i, j;

i = 0;
if (striptype != RIGHTSTRIP) {
while (i < len && isspace(Py_CHARMASK(s[i]))) {
i++;
}
}

j = len;
if (striptype != LEFTSTRIP) {
do {
j--;
} while (j >= i && isspace(Py_CHARMASK(s[j])));
j++;
}

if (i == 0 && j == len && PyString_CheckExact(self)) {
Py_INCREF(self);
return (PyObject*)self;
}
else
return PyString_FromStringAndSize(s+i, j-i);
}

它首先从左边开始递增变量i,直到找到一个非空格字符,然后从右边开始递减j直到找到一个非空格字符。最后返回 ij 之间的字符串

PyString_FromStringAndSize(s+i, j-i)

但另一方面,the strip which removes the set of characters , 稍微复杂但相当相似。

Py_LOCAL_INLINE(PyObject *)
do_xstrip(PyStringObject *self, int striptype, PyObject *sepobj)
{
char *s = PyString_AS_STRING(self);
Py_ssize_t len = PyString_GET_SIZE(self);
char *sep = PyString_AS_STRING(sepobj);
Py_ssize_t seplen = PyString_GET_SIZE(sepobj);
Py_ssize_t i, j;

i = 0;
if (striptype != RIGHTSTRIP) {
while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
i++;
}
}

j = len;
if (striptype != LEFTSTRIP) {
do {
j--;
} while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
j++;
}

if (i == 0 && j == len && PyString_CheckExact(self)) {
Py_INCREF(self);
return (PyObject*)self;
}
else
return PyString_FromStringAndSize(s+i, j-i);
}

它和前一个一样,但是每次都有额外的memchr(sep, Py_CHARMASK(s[j]), seplen)检查。因此,时间复杂度变为 O(N * M),其中 M 是要剥离的实际字符串的长度。

关于python - Python 的 strip() 的运行时间是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27684578/

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