Victor Henriquez
Victor Henriquez

Reputation: 1449

Time complexy: growing list in nested for-loops

In this code:

test = [1] * 10
result = []
for i in test:
    if not result:
        result = [i,i,i]
    else:
        new_result = []
        for j in result:
            for k in range(3):
                new_result.append(i + k)
        result = new_result

The outer loop runs n times. The inner loop, if I'm not wrong, runs 3^n

The Big O of this algorithm is 3^n * n. Am I right?

Upvotes: 1

Views: 45

Answers (1)

Ramy M. Mousa
Ramy M. Mousa

Reputation: 5943

It's just 3^n. if you try this after your execution:

print(len(result)) #result: 59049
print(3**len(test)) #result: 59049

So yes it grows exponentially relative to the size of n as the output of result will grow as follows by each iteration:

3
9
27
81
243
729
2187
6561
19683
59049

I used timeit to print out the execution time as n grows

n = 10 # Time:  0.020012678000000002
n = 11 # Time:  0.057932331000000004
n = 12 # Time:  0.15807880600000002

You see where it's going in terms of time.

here is the code I used:

import timeit
test = [1] * 12
result = []
start = timeit.default_timer()

print(test)
for i in test:
    if not result:
        result = [i,i,i]
        print(result)
    else:
        new_result = []
        print(len(result))
        for j in result:
            for k in range(3):
                new_result.append(i + k)
        result = new_result

stop = timeit.default_timer()

print('Time: ', stop - start) 

Upvotes: 1

Related Questions