jihoonerd/Data_Structures_and_Algorithms_in_Python

Chap3, R-3.27, the time complexity of `example5`

shenxiangzhuang opened this issue · 1 comments

I think there are something wrong in the solution of Chap3, R-3.27.

Firstly, the time complexity of example5 should be O(n^3).

Then, there are some problems when we collect data from example5 for plot. I think we can do it by changing the code a little bit. Like this:

def example5(A, B):
    n = len(A)
    count = 0
    num_calc = 0
    for i in range(n):
        total = 0
        for j in range(n):
            for k in range(1+j):
                total += A[k]
                num_calc += 1
        if B[i] == total:
            count+=1
    return count, num_calc

def get_time_complexity_2(n=100):
    op_nums = []
    for i in range(1, n):
        A = np.random.randint(0, 100, size=(i, ))
        B = np.random.randint(0, 100, size=(i, ))
        _, num_calc = example5(A, B)
        op_nums.append(num_calc)
    plt.plot(op_nums)
    plt.plot(range(n), [i**2 for i in range(n)])
    plt.plot(range(n), [i**3 for i in range(n)])
    plt.legend(['example5', '$n^2$', '$n^3$'])
    plt.title('example5')
    plt.show()

And the plot should like this:
image

@shenxiangzhuang I double checked it and you are right, not sure why I introduce unnecessary variable count_bo for doing this. 😓 Again, thanks for suggesting good feedbacks.