Mini-projets algorithmique, corrigé TP KNN, news, notebooks IA
This commit is contained in:
81
algorithmes/mini-projets/02_cartes/starter.py
Normal file
81
algorithmes/mini-projets/02_cartes/starter.py
Normal file
@@ -0,0 +1,81 @@
|
||||
# Projet 02 — Le Tri de Cartes
|
||||
# Algorithme : Tri par insertion
|
||||
|
||||
NOMS_VALEURS = {11: "Valet", 12: "Dame", 13: "Roi", 14: "As"}
|
||||
|
||||
def nom_carte(carte):
|
||||
"""Retourne une représentation lisible d'une carte."""
|
||||
valeur, couleur = carte
|
||||
nom = NOMS_VALEURS.get(valeur, str(valeur))
|
||||
return f"{nom} de {couleur}"
|
||||
|
||||
def afficher_main(main):
|
||||
"""Affiche toutes les cartes d'une main."""
|
||||
print("Main :", " | ".join(nom_carte(c) for c in main))
|
||||
|
||||
def tri_insertion_cartes(main):
|
||||
"""
|
||||
Trie la main de cartes par valeur croissante (tri par insertion).
|
||||
Chaque carte est un tuple (valeur, couleur).
|
||||
On trie selon le premier élément du tuple : la valeur.
|
||||
"""
|
||||
for i in range(1, len(main)):
|
||||
x = main[i]
|
||||
j = i
|
||||
# TODO : compléter la condition du while
|
||||
# Indice : on compare les valeurs (main[j-1][0] et x[0])
|
||||
while j > 0 and ...:
|
||||
main[j] = main[j - 1]
|
||||
j -= 1
|
||||
main[j] = x
|
||||
return main
|
||||
|
||||
def chercher_carte(main_triee, valeur):
|
||||
"""
|
||||
Recherche dichotomique : retourne True si une carte de cette valeur
|
||||
est dans la main triée, False sinon.
|
||||
"""
|
||||
a = 0
|
||||
b = len(main_triee) - 1
|
||||
while a <= b:
|
||||
m = (a + b) // 2
|
||||
valeur_m = main_triee[m][0] # on compare les valeurs
|
||||
if valeur_m == valeur:
|
||||
return True
|
||||
elif valeur_m < valeur:
|
||||
# TODO
|
||||
pass
|
||||
else:
|
||||
# TODO
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
# --- Programme principal ---
|
||||
main = [
|
||||
(7, "Coeur"),
|
||||
(2, "Pique"),
|
||||
(11, "Trèfle"),
|
||||
(5, "Carreau"),
|
||||
(14, "Coeur"),
|
||||
(9, "Pique"),
|
||||
(3, "Carreau"),
|
||||
]
|
||||
|
||||
print("=== Le Tri de Cartes ===")
|
||||
print()
|
||||
print("Avant le tri :")
|
||||
afficher_main(main)
|
||||
|
||||
tri_insertion_cartes(main)
|
||||
|
||||
print()
|
||||
print("Après le tri par insertion :")
|
||||
afficher_main(main)
|
||||
|
||||
print()
|
||||
# Test de recherche
|
||||
for valeur_cherchee in [7, 12, 14, 6]:
|
||||
resultat = chercher_carte(main, valeur_cherchee)
|
||||
nom = NOMS_VALEURS.get(valeur_cherchee, str(valeur_cherchee))
|
||||
print(f"Cherche {nom} : {'trouvé !' if resultat else 'absent'}")
|
||||
Reference in New Issue
Block a user