3

What is the time/space complexity of split/strip/open (in-built python functions)?

Does anyone know where i can look up on the time/space complexity of these functions?

3
  • 2
    I do not know where you can find that information, but couldn't you just time the functions yourself and then plot the results on a graph and see if it is linear/parabolic/etc..? Commented Mar 12, 2019 at 3:34
  • 2
    wiki.python.org/moin/TimeComplexity Commented Mar 12, 2019 at 4:00
  • 1
    @RockyLi has the exact answer to the question, don't bother with timing or anything like that unless you need an empirical result instead of a formal statement. Commented Mar 12, 2019 at 4:25

1 Answer 1

9

The exact answer will depend on what properties are fed into the function. The easiest way to find out would probably be to examine the source code for those functions. The python source code can be found here.

Lets take a look at the source for split. The code runs different loops depending on the properties. This is the loop for splitting by whitespace.

    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++;

In this code, the function will look at each character in the string (unless the maxcount is reached). The inner most loops will run n times for a string of size n. Time complexity is O(n)

The source for strip steps through each character in the string.

    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++;
}

This gives strip a time complexity of O(n).

The Source for open() shows no loops. This is what we would expect. There is nothing to loop through.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Really helped me clarify the time complexity of those in built functions!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.