tg4/Chapitre 3 - Modularité/TP Test unitaires.py
2023-12-06 08:35:46 +01:00

60 lines
1.8 KiB
Python

# === Boite noir === #
def deuxieme_plus_grand(tableau):
if len(tableau) < 2:
return None
# Trie le tableau par ordre décroissant
tableau_trie = sorted(tableau, reverse=True)
# Renvoie le deuxième élément du tableau trié
return tableau_trie[1]
assert deuxieme_plus_grand([1, 2, 3, 4, 5]) == 4
assert deuxieme_plus_grand([5, 4, 3, 2, 1]) == 4
assert deuxieme_plus_grand([9, 2, 7, 5, 1, 8, 3, 6]) == 8
assert deuxieme_plus_grand([-2, -7, -1, -5, -3]) == -2
assert deuxieme_plus_grand([]) == None
assert deuxieme_plus_grand([2]) == None
# === Boite blanche === #
def deuxieme_plus_grand(tableau):
deuxieme = None
grand = tableau[0]
for i in range(1, len(tableau)):
if tableau[i] > grand:
deuxieme = grand
grand = tableau[i]
return deuxieme
# assert deuxieme_plus_grand([1, 2, 3, 4, 5]) == 4
# assert deuxieme_plus_grand([5, 4, 3, 2, 1]) == 4
# assert deuxieme_plus_grand([]) == None
# assert deuxieme_plus_grand([2]) == None
def tableau_max(tableau):
plus_grand = None
for valeur in tableau:
if plus_grand is None or valeur > plus_grand:
plus_grand = valeur
return plus_grand
def plus_grand_inferieur(tableau, maximum):
plus_grand = None
for valeur in tableau:
if (plus_grand is None or valeur > plus_grand) and valeur < maximum:
plus_grand = valeur
return plus_grand
def deuxieme_plus_grand(tableau):
plus_grand = tableau_max(tableau)
return plus_grand_inferieur(tableau, plus_grand)
assert deuxieme_plus_grand([1, 2, 3, 4, 5]) == 4
assert deuxieme_plus_grand([5, 4, 3, 2, 1]) == 4
assert deuxieme_plus_grand([9, 2, 7, 5, 1, 8, 3, 6]) == 8
assert deuxieme_plus_grand([-2, -7, -1, -5, -3]) == -2
assert deuxieme_plus_grand([]) == None
assert deuxieme_plus_grand([2]) == None