简体   繁体   中英

Python - How to calculate this recursive function time complexity?

I wanted to solve the tower hopper problem in as much ways that I can and calculate each way's time complexity (just for self practice). One of the solution is this:

def is_hopable(arr):
    if len(arr) < 1 or arr[0] == 0:
        return False
    if arr[0] >= len(arr):
        return True
    res = False
    for i in range(1,arr[0]+1):
        res = res or is_hopable(arr[i:]) # This line  
    return res

I know the general idea of recursive time complexity calculation but I'm having trouble to analyze the commented line (inside the for loop). Usually I calculate the time complexity with T(n) = C + T(that line) and reduce it with a general expression (for example T(nk)) until I reach the base case and can express k with n, but what is the time complexity of that for loop?

The complexity of that for loop could be up to O(n^2) because every iteration of the loop (up to n iterations) do a slice arr[i:] that return a copy of arr without first i elements O(n) . With that in mind overall time is O(n^3) .

Mentioned upper bound is tight.
Example: arr = [n-1, n-2, n-3, ..., 1, 1]
Alternative form: arr[i] = n - 1 - i for all i , 0 <= i < n - 1 , and arr[n-1] = 1 where n is length of arr .

The recurrence to calculate amount of elemental operations (avoiding the use of constant) can be stated as:
1

Simplify summation:
2

Evaluate (unroll) lesser terms of T and search a lower bound:
3

Use formula of sum of squares from 1 to n :
5

As T(n) lower bound is a polynomial of degree 3 we have found that such instance of the problem running time is Ω(n^3) proving that the upper bound for the problem ( O(n^3) ) is tight.

Side note:
If you use as parameters original array and current index the runtime of for loop will be O(n) and overall time O(n^2) .

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