diff --git a/src/util.py b/src/util.py index 451bb9870e39c6149281c107503af3b9fab97f83..2bac69f5619f2676ef4dd67742558ca576552f68 100644 --- a/src/util.py +++ b/src/util.py @@ -26,22 +26,30 @@ def compare(a, b): return res def recherche_dichotomique(x, l, cmp = compare): - """ - :param x: (any) un élément - :param l: (list) une liste - :return: (bool) True si x appartient à l, False sinon - :CU: x doit être comparable aux éléments de l, - l est triée - :Exemples: + """Renvoie l'unique `index` vérifiant : + * 0 ≤ index ≤ len(liste) + * ∀j ∈ [0 ; len(liste)[, si j < index alors liste[j] < x + sinon liste[j] ≥ x + Cet indice `index` indiquera soit la place de l'élément x dans la liste, + soit la place du fils susceptible de contenir l'élément x recherché + dans un arbre de recherche. - >>> recherche_dichotomique(1, []) + Précondition : `liste` est triée par ordre croissant + Exemple(s) : + >>> recherche_dichotomique(3, [1, 3, 5]) + (True, 1) + >>> recherche_dichotomique(4, [1, 3, 5]) + (False, 2) + >>> recherche_dichotomique(0, [1, 3, 5]) + (False, 0) + >>> recherche_dichotomique(42, [1, 3, 5]) + (False, 3) + >>> recherche_dichotomique(42, []) (False, 0) - >>> l = list(range(10)) - >>> recherche_dichotomique(5, l) - (True, 5) - >>> recherche_dichotomique(5.5, l) - (False, 6) """ + # précondition : liste triée + assert all(l[k] <= l[k+1] for k in range(len(l) - 1)) + # votre code ici sans le return taille = len(l) debut, fin = 0, taille index = 0 @@ -55,6 +63,11 @@ def recherche_dichotomique(x, l, cmp = compare): else: fin = milieu index = milieu + # postcondition + assert 0 <= index <= len(l) + assert all(j < index and l[j] < x or l[j] >= x + for j in range(len(l))) + # retour return (False, index) ## LOIC