Con poche righe di codice puoi ottenere un’animazione dell’ordinamento dei numeri da 1 a 50 mescolati a caso.
Web VPython
Con un po’ di impegno ulteriore puoi aggiungere l’interattività
- I numeri sono mescolati a caso o disposti in ordine decrescente?
- La velocità di esecuzione da 1 a 5
- La coppia che viene scambiata è colorata di blu.
Web VPython 3.2
from random import shuffle
#----------------------------------------------------------------
def bubble_sort():
global STOP
n = len(lista)
for i in range(n-1):
for j in range(n-1-i):
if(STOP): return
if(lista[j] > lista[j+1]):
temp = lista[j]
lista[j] = lista[j+1]
lista[j+1] = temp
g1.data = [(x,y) for (x,y) in enumerate(lista)]
g2.data = [(j+1, lista[j+1])]
sleep(RITARDO)
g1.data = [(x,y) for (x,y) in enumerate(lista)]
g2.data = []
STOP = True
#----------------------------------------------------------------
def bind_veloc(evt):
global VELOCIT, RITARDO
x = evt.value
VELOCIT = x
wtext_veloc.text = x
RITARDO = 0.05 - VELOCIT/100
def bind_casuale(evt):
global STOP
STOP = True
shuffle(lista)
g2.data = []
g1.data = [(x,y) for (x,y) in enumerate(lista)]
def bind_decresc(evt):
global STOP
STOP = True
lista.sort(reverse=True)
g2.data = []
g1.data = [(x,y) for (x,y) in enumerate(lista)]
def bind_ordina(evt):
global STOP
if(STOP):
STOP = False
bubble_sort()
#----------------------------------------------------------------
NUMERO = 50
VELOCIT_0 = 3
VELOCIT = VELOCIT_0
RITARDO = 0.05 - VELOCIT/100
STOP = True
c = canvas()
c.append_to_caption("Ordine iniziale "); button_casuale = button(bind=bind_casuale, text="Casuale");
c.append_to_caption(" ") ; button_decresc = button(bind=bind_decresc, text="Decrescente");
c.append_to_caption("t") ; button_ordina = button(bind=bind_ordina , text="ORDINA!");
c.append_to_caption("nnVelocità ") ; slider_veloc = slider(bind=bind_veloc , min=1, max=5, step=0.1, value=VELOCIT)
c.append_to_caption(" ") ; wtext_veloc = wtext(text=VELOCIT)
c.append_to_caption("nn")
g = graph(ymax=NUMERO*1.1)
g1 = gvbars(color = color.gray(.5)) # Barre verticali lista
g2 = gvbars(color = color.blue) # Barre verticali "scambiati"
lista = list(range(1, NUMERO+1))
shuffle(lista)
g1.data = [(x,y) for (x,y) in enumerate(lista)]
g2.data = []
c.delete()