Количество выполнений суммы + = 1 во вложенном цикле - PullRequest
0 голосов
/ 03 марта 2020

Итак, я застрял при попытке выяснить, почему число выполнений sum += 1 равно (2n * n) в этом коде.

n = 5  # n can be anything
sum = 0
for i in range(n):
    for j in range(n):
        sum += 1
print(sum)

Я знаю, что для простых циклов sum += 1 будет выполняться 3n раз, но не знаю, как объяснить математику выше. Спасибо.

edit: Вот несколько картинок выполнения математики, так как кажется, что есть путаница. Примечание: я не ищу Big (O), но сложность времени, прежде чем мы оценим Big (O). Page 1

Page 2

1 Ответ

1 голос
/ 03 марта 2020
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
...