Home > Software design >  determining the time complexity for particular code
determining the time complexity for particular code

Time:11-17

I want to determine complexity for second_max function but how do i do it, how to determine time complexity for my code and for any other code

from random import randint
import sys
from bigO import BigO

def r_array(r_i= 0,r_e = 100,step=10):
    return [randint(r_i, r_e) for i in range(r_i, r_e, step)]

def second_max(arr):
    n_max = -sys.maxsize
    n_s_max = -sys.maxsize

    for i in range(0, len(arr)):
            if arr[i] > n_max:
                n_s_max = n_max
                n_max = arr[i]
            elif (arr[i] < n_max and arr[i] > n_s_max):
                n_s_max = arr[i]

    return n_s_max

_lib = BigO()
cmplx = _lib.test(second_max, "")

array = r_array(step=20)
print(f"original array: {array}")
second_large_num = second_max(array)
print(second_large_num)

I consider my code(second_max) has o(n) complexity but not sure.

i tried bigO module but it returns

for i in range(len(array) - 1):
TypeError: object of type 'int' has no len()

CodePudding user response:

First of all, the bigO python module can only estimate the time complexity. It is theoretically impossible for a program to "calculate" the time complexity of all possible algorithms. This is similar to the halting problem.

So don't rely on that module for finding out the time complexity. There is no method for determining the time complexity that will always work. For some complex, known algorithms there is even no proof yet of what their time complexity is.

A second thing to consider is what

  • Related