简体   繁体   中英

Python: Calculate and reduce time complexity (Unsure if solution is correct)

I have a program below and I calculated the time complexity as O(n^2) due to the nested loops, but I am unsure if it is correct since I have read that if you are looping in a constant range then the runtime is constant. I am a bit confused about this.

def f(data, k):
    n = len(data)
    output = [0]*(n-k)
    for i in range(n-k):
        for j in range(k):
            output[i] += data[i+j]

    return output

The second part is to reduce the time complexity. I have a solution and I think the improved program has complexity of O(n), but I am also unsure about the built-in function sum(). I would like to know if what I did with sum() below is constant or linear time. If it is linear time, then the complexity would be O(n^2) again. What can I do to improve it?

def g(data, k):
    n = len(data)
    output = []
    if data: # If there are elements in the array
        for i in range(n-k):
            s = sum(data[:k])
            output.append(s)
            data.pop(0)

        return output

The complexities of the two programs are (nearly) the same. The complexity of the built in function is still O(n) which makes the whole complexity, once again, O(n^2) .

Regarding the doubt about constant complexity loops in the first program, it is not case because the loop does depend on the input length. A constant loop is a loop which always does a fixed (constant) number of steps.

The algorithm can be improved by a factor of n, making the complexity O(n) . To achieve so you should use the notion of prefix sums.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM