n = 5 # n can be anything
sum = 0
for i in range(n): # this executes n times
for j in range(n): # this executes n times as well
sum += 1
print(sum)
Этот код выполняется за O(n^2)
время, потому что вы умножаете первое for
l oop (с i
), которое выполняется n
раз, на for
l oop (с j
), который также выполняется n
раз.
Таким образом, n * n - это частота выполнения sum += 1
.
Вы можете добавить оператор print
и убедиться в этом сами. Следующим образом:
from itertools import count
n = 5 # n can be anything
sum = 0
c = count()
for i in range(n): # this executes n times
for j in range(n): # this executes n times as well
sum += 1
print(f'This is the {next(c)+1} execution')
print(sum)
Вывод:
This is the 1 execution
This is the 2 execution
This is the 3 execution
This is the 4 execution
This is the 5 execution
This is the 6 execution
This is the 7 execution
This is the 8 execution
This is the 9 execution
This is the 10 execution
This is the 11 execution
This is the 12 execution
This is the 13 execution
This is the 14 execution
This is the 15 execution
This is the 16 execution
This is the 17 execution
This is the 18 execution
This is the 19 execution
This is the 20 execution
This is the 21 execution
This is the 22 execution
This is the 23 execution
This is the 24 execution
This is the 25 execution
25