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

标签 python python-2.7 python-internals

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/

相关文章:

python - 为什么我的 pyinstaller 不提取任何 exe 文件

python - 在 python 27 中,如何将带参数的方法传递给类的 __init__()?

python - 为什么当我完成解码和编码时,我的字符串末尾有一个换行符?

python - 带有自定义中间件的 django 自定义身份验证后端(用户名、密码和 token Absed 身份验证)

python - 'is' 运算符对 float 的表现出乎意料

python - 数据流 Python SDK Avro 源/同步

python - lambda 中生成器的行为对 future 的变化安全吗?

python - 运行时错误 : lost sys. 标准输出

python - pandas pivot_table 百分位数/分位数

python - Python 何时识别/不识别 main 中的变量?