python课程中关于效率的辩论

insrf1ej  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(338)
n = int(input())
L = []
for i in range(n):
    for j in range(n):
        L.append(i * j)
for i in range(n):
    l = L[:] + [i]

下面代码的效率是n^3还是n^2?第三个循环是否由于复制运算符而为n^3?

qacovj5a

qacovj5a1#

n = int(input())
L = []
for i in range(n):  # --> O(n+1)                                #!
    for j in range(n): # --> O(n+1(n+1)) = O(n^2+2n+1)          #NESTED!
        L.append(i**j) # --> O(n*n) k=depth of loops -> k*=n -> O(n^2)
for i in range(n): #---> O(n+1)                      #INDEPENDENT NEW LOOP
    l = L[:] + [i] #----> O(n)

### ----> Total = O(2n^2+5n+3) ==> O(n^2)

相关问题