Partition de tableau

Écrire une fonction partition qui prend en paramètres un entier pivot et une liste d’entiers tableau et qui renvoie un tuple composé de trois listes :

  • la première liste contient les indices, dans l'ordre croissant, des valeurs de tableau strictement inférieures à pivot ;
  • la deuxième liste contient les indices, dans l'ordre croissant, des valeurs de tableau égales à pivot ;
  • la troisième liste contient les indices, dans l'ordre croissant, des valeurs de tableau strictement supérieures à pivot.

Exemples

🐍 Script Python
>>> partition(3, [1, 3, 4, 2, 4, 6, 3, 0])
([0, 3, 7], [1, 6], [2, 4, 5])
>>> partition(3, [1, 4, 2, 4, 6, 0])
([0, 2, 5], [], [1, 3, 4])
>>>partition(3, [1, 1, 1, 1])
([0, 1, 2, 3], [], [])
>>> partition(3, [])
([], [], [])
###
# Testsbksl-nlassert partition(3, [1, 3, 4, 2, 4, 6, 3, 0]) == ([0, 3, 7], [1, 6], [2, 4, 5])bksl-nlassert partition(3, [1, 4, 2, 4, 6, 0]) == ([0, 2, 5], [], [1, 3, 4])bksl-nlassert partition(3, [1, 1, 1, 1]) == ([0, 1, 2, 3], [], [])bksl-nlassert partition(3, []) == ([], [], [])bksl-nlbksl-nl# Autres Testsbksl-nlassert partition(3, [3, 3, 3, 3]) == ([], [0, 1, 2, 3], [])bksl-nlbksl-nlbksl-nldef partitionpy-undcorr(pivot, tableau):bksl-nl inferieurs, egaux, superieurs = [], [], []bksl-nl for i, x in enumerate(tableau):bksl-nl if x < pivot:bksl-nl inferieurs.append(i)bksl-nl elif x == pivot:bksl-nl egaux.append(i)bksl-nl else:bksl-nl superieurs.append(i)bksl-nl return inferieurs, egaux, superieursbksl-nlbksl-nlbksl-nlfrom random import randrangebksl-nlbksl-nlxpy-undmini = -50bksl-nlxpy-undmaxi = 51bksl-nlfor test in range(20):bksl-nl taille = randrange(20, 31)bksl-nl tableau = [randrange(xpy-undmini, xpy-undmaxi) for py-und in range(taille)]bksl-nl pivot = randrange(xpy-undmini, xpy-undmaxi)bksl-nl attendu = partitionpy-undcorr(pivot, tableau)bksl-nl assert (bksl-nl partition(pivot, tableau) == attendubksl-nl ), f"Erreur avec {pivot = } et {tableau = }"bksl-nlbksl-nl 5/5

def partition(pivot, tableau):bksl-nl ...bksl-nlbksl-nlbksl-nl# Testsbksl-nlassert partition(3, [1, 3, 4, 2, 4, 6, 3, 0]) == ([0, 3, 7], [1, 6], [2, 4, 5])bksl-nlassert partition(3, [1, 4, 2, 4, 6, 0]) == ([0, 2, 5], [], [1, 3, 4])bksl-nlassert partition(3, [1, 1, 1, 1]) == ([0, 1, 2, 3], [], [])bksl-nlassert partition(3, []) == ([], [], [])bksl-nlbksl-nldef partition(pivot, tableau):bksl-nl indicespy-undinferieur = []bksl-nl indicespy-undegal = []bksl-nl indicespy-undsuperieur = []bksl-nl for i in range(len(tableau)):bksl-nl if tableau[i] < pivot:bksl-nl indicespy-undinferieur.append(i)bksl-nl elif tableau[i] > pivot:bksl-nl indicespy-undsuperieur.append(i)bksl-nl else:bksl-nl indicespy-undegal.append(i)bksl-nl return (indicespy-undinferieur, indicespy-undegal, indicespy-undsuperieur)bksl-nlbksl-nl

A

Z