简体   繁体   English

时间复杂度:嵌套 for 循环中的增长列表

[英]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.外循环运行 n 次。 The inner loop, if I'm not wrong, runs 3^n内循环,如果我没记错的话,运行 3^n

The Big O of this algorithm is 3^n * n.这个算法的大 O 是 3^n * n。 Am I right?我对吗?

It's just 3^n .它只是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:所以是的,它相对于n的大小呈指数增长,因为每次迭代result的输出将如下增长:

3
9
27
81
243
729
2187
6561
19683
59049

I used timeit to print out the execution time as n grows我使用timeit打印出随着n增长的执行时间

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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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