Runtime of python's if substring in string

前端 未结 4 558
名媛妹妹
名媛妹妹 2020-12-05 18:43

What is the big O of the following if statement?

if \"pl\" in \"apple\":
   ...

What is the overall big O of how python determ

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 19:09

    I think the best way to find out is to look at the source. This looks like it would implement __contains__:

    static int
    bytes_contains(PyObject *self, PyObject *arg)
    {
        Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
        if (ival == -1 && PyErr_Occurred()) {
            Py_buffer varg;
            Py_ssize_t pos;
            PyErr_Clear();
            if (PyObject_GetBuffer(arg, &varg, PyBUF_SIMPLE) != 0)
                return -1;
            pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self),
                                 varg.buf, varg.len, 0);
            PyBuffer_Release(&varg);
            return pos >= 0;
        }
        if (ival < 0 || ival >= 256) {
            PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
            return -1;
        }
    
        return memchr(PyBytes_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
    }
    

    in terms of stringlib_find(), which uses fastsearch().

提交回复
热议问题