nsi:premiere:tableau:tri:critere
Ceci est une ancienne révision du document !
Warning: Undefined array key 1 in /home/goupillf/wiki.goupill.fr/lib/plugins/codeprettify/syntax/code.php on line 172
Warning: Undefined array key 1 in /home/goupillf/wiki.goupill.fr/lib/plugins/codeprettify/syntax/code.php on line 172
Warning: Undefined array key 1 in /home/goupillf/wiki.goupill.fr/lib/plugins/codeprettify/syntax/code.php on line 149
Warning: Trying to access array offset on value of type null in /home/goupillf/wiki.goupill.fr/lib/plugins/codeprettify/syntax/code.php on line 149
Warning: Undefined array key 2 in /home/goupillf/wiki.goupill.fr/lib/plugins/codeprettify/syntax/code.php on line 214
Warning: Undefined array key 2 in /home/goupillf/wiki.goupill.fr/lib/plugins/codeprettify/syntax/code.php on line 214
Warning: Undefined array key 2 in /home/goupillf/wiki.goupill.fr/lib/plugins/codeprettify/syntax/code.php on line 214
Warning: Undefined array key 2 in /home/goupillf/wiki.goupill.fr/lib/plugins/codeprettify/syntax/code.php on line 214
Tri, Exercice : Choix d'un critère
Supposons que les éléments à trier n'ait pas un ordre évident. Par exemple supposons que notre tableau soit :
[
("chaussettes", "4NB517", 3.50),
("moutarde", "8XG356", 2.50),
("cahier", "2KL649", 2.80),
("saucisson", "1SR912", 5.65),
("crayons", "3GE416", 3.50),
("gâteaux", "8OU996", 2.80),
("bananes", "7JV824", 1.95)
]
Nous voulons trier par prix croissante et, si les prix sont les mêmes, par nom de produit.
On définit alors une fonction par_prix(a,b) dont le rôle est de dire si a < b selon notre critère de prix. La fonction renvoie donc True ou False, True quand on peut dire que a < b.
Cette fonction est soumise comme critère à un tri par sélection ce qui permet de trier le tableau.
Dans le fichier choix_critere.py,
- complétez la fonction
par_prix, - modifiez la fonction
tri_par_selectionpour qu'elle tienne compte du critère choisi, - exécutez pour voir si le test produit le résultat attendu.
# choixcritere.py
def par_prix(a, b):
'''
a, b: items du tableau
renvoie True si on doit considérer a < b
'''
# à compléter
return True
def tri_par_selection(tab, critere):
'''
tab: tableau à trier
critere: fonction de comparaison
'''
n = len(tab)
for i in range(n-1):
i_min = i
for j in range(i+1,n):
if tab[j] < tab[i_min]:
i_min = j
if i != i_min:
tab[i_min], tab[i] = tab[i], tab[i_min]
# tests
if __name__=="__main__":
T = [
("chaussettes", "4NB517", 3.50),
("moutarde", "8XG356", 2.50),
("cahier", "2KL649", 2.80),
("saucisson", "1SR912", 5.65),
("crayons", "3GE416", 3.50),
("gâteaux", "8OU996", 2.80),
("bananes", "7JV824", 1.95)
]
print("tableau à trier =", T)
print("Exécution du tri...")
tri_par_selection(T, par_prix)
print("tableau trié = ", T)
nsi/premiere/tableau/tri/critere.1670500957.txt.gz · Dernière modification : de goupillwiki
