Python - List sorting without Sort()

Asked

Viewed 87 times

-3

I was studying this list ordering code and there are some things I didn’t understand:

  • Why is it necessary to break?
  • Why leave the else ident with the if and without the break doesn’t work?
  • Why with the break the else is identuated 4 spaces behind the if?
  • By placing the break 4 spaces back, the code enters the else the first time and then no more. Why?
lista = [11, 11, 15, 12, 13, 9, 4, 1, 2, 1, 11, 15, 41, 42, 40]
ordenado = []

for numero in lista:
    for chave, valor in enumerate(ordenado):
        if numero < valor:
            ordenado.insert(chave, numero)
            break
    else:
        ordenado.append(numero)
        
print(ordenado)
  • To help with a point, in Python a for may have a else associated with it. Basically, if the loop is not interrupted by a break, he enters the else, see the documentation

1 answer

0


This code take the values of lista and goes putting in ordenado. In the first iteration of for ordenado is empty then, the instruction jumps to the else and add value 11 in ordenado. In the second iteration the instruction already enters the second for and compares if numero < valor, and only compares with 11 because this is the only ordered element so far, then the other 11 is added to ordenado in block else. In the third iteration occurs the same as the second and 15 is added to the ordenado. In the fourth iteration numero = 12, the second for compare if numero < valor numero=12 with (11,11,15), when it comes to the comparison 12 < 15 the instruction enters the if and inserts the 12 into the second position, previously occupied by the 15 that will now occupy the 3rd. In the 4th iteration, note that numero = 12 and this was exchanged with the 15 no if, that means that ordenado = [11,11,12,15], poi the 15 was pushed to the next position, the list ordenado which had 3 values (11,11,15) now has 4, so if you do not find a break there will be a new comparison 12 < 15, then another change occurs, now we have another 12 in the 4th position and the 15 is pushed again to the 5th. Again ordenado increased one more element so the previous Oxyclo repeats endlessly.

1 - Prevents the change to be repeated for the same value 12 and 15 example as said before.

2 - The else this ident with the second is so that it runs every time, it is where list values are added to ordenado and the break prevents the loop , repeating the one before, if it was idented with the if or the number was changed or was added at the end list, this would prevent all of the lista were added to ordenado.

3 - Why it needs to be executed every time, in this example, 15 times to add all values of lista in ordenado

4 - In that case Else would be out of the loop so it runs only once and at the end of the execution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.