What is the cost function of the large value of this algorithm?

How would you describe the following in Big-O notation?

rotors = [1,2,3,4,5 ...]
widgets = ['a', 'b', 'c', 'd', 'e' ...]

assert len(rotors) == len(widgets)

for r in rotors:
    for w in widgets:
        ...

    del widgets[0]
+3
source share
7 answers

It O (n ^ 2). You can see that the amount of execution of the inner loop:

n + (n - 1) + (n - 2) + ... + 1

because one widget is removed every iteration of the outer loop. This is (n ^ 2 + n) / 2, which is O (n ^ 2).

+7
source

as you go through both O (n ^ 2) loops.

+5
source

- :

assert len(rotors) == len(widgets)

O (n 2) , , , O (m * n).

+4

O (n ^ 2).

+3

O (n ^ 2), , .

The first loop you have n widgets.
The second loop you have n-1 widgets.
...
The n-1 loop you have 2 widgets.
The n loop you have 1 widgets.

, Big-O, 1/2.

, n + (n-1) +... + 2 + 1 = n (n + 1)/2. N , n ^ 2/2, O (n ^ 2)

+2

, , , . , , O (n ^ 2), , , . , , , , O (1), O (n ^ 2).

+2
source

Yes, why these big problems are always hard to understand. But if I were to assume that I would say O (n ^ 2), since you go through 2 for loops doing some operation each time.

0
source

Source: https://habr.com/ru/post/1744174/


All Articles