Avancé
🧠 Fondamentaux
30 XP
0 personnes ont réussi
Match case sur des tuples
Le vrai pouvoir du pattern matching, c'est le matching structurel : tu peux matcher sur la structure d'un tuple ou d'une liste et en extraire des valeurs en meme temps.
Par exemple, pour analyser un point 2D : match point: case (0, 0): return 'origine' case (0, y): return f'axe Y a y={y}' case (x, 0): return f'axe X a x={x}' case (x, y): return f'point ({x}, {y})'
Dans case (0, y), Python vérifie que le premier élément vaut 0, et capture le deuxieme dans la variable y. C'est la destructuration.
Écris une fonction décrire_point(point) qui prend un tuple (x, y) et renvoie : (0, 0) : 'origine' (x, 0) ou x > 0 : 'axe X positif' (x, 0) ou x < 0 : 'axe X negatif' (0, y) ou y > 0 : 'axe Y positif' (0, y) ou y < 0 : 'axe Y negatif' sinon : 'quadrant' suivi du numéro (1 si x>0 et y>0, 2 si x<0 et y>0, 3 si x<0 et y<0, 4 si x>0 et y<0)
Exemple : décrire_point((0, 0)) renvoie 'origine' décrire_point((3, 0)) renvoie 'axe X positif' décrire_point((3, 4)) renvoie 'quadrant 1'
Tests (3/5)
Origine
assert décrire_point((0, 0)) == 'origine'
Axe X positif
assert décrire_point((3, 0)) == 'axe X positif'
Quadrant 1
assert décrire_point((3, 4)) == 'quadrant 1'
+ 0 tests cachés
Indices (3 disponibles)
Solution officielle
def decrire_point(point):
match point:
case (0, 0):
return 'origine'
case (x, 0) if x > 0:
return 'axe X positif'
case (x, 0) if x < 0:
return 'axe X negatif'
case (0, y) if y > 0:
return 'axe Y positif'
case (0, y) if y < 0:
return 'axe Y negatif'
case (x, y) if x > 0 and y > 0:
return 'quadrant 1'
case (x, y) if x < 0 and y > 0:
return 'quadrant 2'
case (x, y) if x < 0 and y < 0:
return 'quadrant 3'
case (x, y) if x > 0 and y < 0:
return 'quadrant 4'