+ 1
Bubble method. Because sometimes it works and sometimes it does not
#Bubble method to sort array from random import randint A = [randint(1,20) for elem in range(6)] print (A) while (True): ordered = True for pos, val in enumerate(A[:len(A)-1],0): if (val > A[pos+1]): del A[pos] A.insert(pos+1,val) ordered = False if (ordered): break print (A) https://code.sololearn.com/cQBzSHn81sds
7 Antworten
+ 9
You should save the value you want to insert to the list, before deleting it right away. Take a look below and observe the part with the 'b' variable:
from random import randint
A = [randint(1,20) for elem in range(6)]
print (A)
while (True):
ordered = True
for pos, val in enumerate(A[:len(A)-1],0):
if (val > A[pos+1]):
b = A[pos]
del A[pos]
A.insert(pos+1,b)
ordered = False
if (ordered):
break
print (A)
+ 7
val = A[pos]
But when you iterate through the list and change it by inserting an item, it sometimes happen that you insert val on the position which is to be iterated in the next step. And you are stuck with it, that's why the repeating occurences:
Add this line before 'del A[pos]':
print(pos, A[pos], val)
and run the code a couple of times until it goes wrong. Then see where it broke - it assigned wrong value to val, because you changed the list during the iteration process.
+ 1
El error ocurre por que no se guarda el numero a insertar y se elimina de la lista en la siguiente iteración
uy se adelantaron!
+ 1
@javer Why if val is the value of A[pos] ?
Ocurre que cuando se cumple la condicion de valor> a[pos+1] el programa elimina A[pos] en este caso eliminara el valor de A en la posición donde se encuentre valor, Valga la renduancia
(así lo entiendo yo)
0
@kuba.. @Christian.. Why if val is the value of A[pos] ?
0
Thanks @kuda.. but if I check the code, there is never wrong and I need not save the value A[pos]. Then why do this if it works ?
from random import randint
A = [randint(1,20) for elem in range(10)]
print (A)
while (True):
ordered = True
for pos, val in enumerate(A,0):
if (pos == len(A)-1): continue
if (val > A[pos+1]):
del A[pos]
A.insert(pos+1,val).
ordered = False
if (ordered):
break
print (A)
https://code.sololearn.com/cdWzh39Bial2
0
el problema sucede por que el for hace la funcion de un parametro por valor copia el arreglo original y lo voloca de forma independiente y cuando se modifica el arreglo original este no afecta la copia que recore el for.