Chapter 16 · Course 2 c16-m02
Why is one part of the job so slow?
Your goal Diagnose an overloaded partition and choose a suitable redistribution without assuming it removes every imbalance.
The lesson, the vocabulary, the worked example and the mission are separate blocks. You can follow them in order or return to the one you need.
Video explanation
This English explanation has English subtitles. Its examples may use a separate practice dataset; use the data stated in the written mission for your answers.
Story · optional context
The story so far
You are Aster Motors' new data recruit. Luca was hurt when a car resembling Noctis 01 crashed; the prototype is missing and Voss wants to blame you. Mara Sol and Imani are searching many trips for the test shell. In their first job, almost every worker waits for one worker still handling passages near depot D7. This delay may hide a lead behind a long queue of computation.
This lesson stands alone. Spark divides data into partitions processed by tasks. A shuffle moves rows between tasks to group or join them. Skew happens when one task receives much more work than the others. You will measure the imbalance on 18 fictional rows, read repartition(), and learn why moving rows does not always solve the D7 problem.
Before the lesson
Purpose of this course
Diagnose an overloaded partition and choose a suitable redistribution without assuming it removes every imbalance.
Topics covered
Explain partition, task, shuffle, and skew using a small example.; Calculate maximum load and compare it with a typical load.; Explain what repartition(4, "trip_id") may improve and what later grouping by depot does.; Check that redistribution preserves all 18 trips and four depot counts.
What you will learn
- Explain partition, task, shuffle, and skew using a small example.
- Calculate maximum load and compare it with a typical load.
- Explain what
repartition(4, "trip_id")may improve and what later grouping by depot does. - Check that redistribution preserves all 18 trips and four depot counts.
PART 1 · THE LESSON
Understand step by step
Lesson · explanation
A clue can hide behind a slow task
You are Aster Motors' new data recruit. Luca was hurt when a car resembling Noctis 01 crashed; the prototype is missing, and Voss wants to blame you. Mara and Imani search for trips by a test shell near depot D7. Their job appears stuck: three workers finish while one continues for a long time. Voss proposes deleting trips he calls repetitive.
Deleting rows for speed would be risky. Repeated passages near D7 might form the very clue the team seeks. Before changing data, understand why computation waits. This lesson's small copy has eighteen fictional trips and no original case data. It lets you measure a workload difference and consider a better distribution.
Spark is a tool for processing large datasets by sharing work. Picture a classroom where several students sort cards at once. Each receives a pile; if three piles are small and one huge, the class waits for the student with the large pile. Spark workers run tasks on pieces of data called partitions.
This lesson stands alone. You will learn partition, task, grouping key, shuffle and imbalance, often called skew. Your mission is to diagnose the big pile without inventing missing trips. The meeting adds story pressure but no actual timer. Python and PySpark examples describe a local copy, without a paid cluster or original-file changes.
Pause and think
Why is Voss's suggestion to delete repetitive trips risky?
See the explanation
They have not been proven duplicates; deletion could erase the D7 clue and alter the counts.
Lesson · explanation
Understand partitions, tasks and workers
A partition is a piece of data Spark can give to a task. A task performs a specific step on that piece, while a worker is a process or machine that runs tasks. Picture a library: split a stack of cards into packets, then give each librarian a packet to sort. Several packets allow parallel work.
If packets have five, five, four and four cards, the librarians have similar workloads. If they have two, two, two and twelve, three librarians finish quickly and wait. That stage's time can depend on the longest task. Adding workers may not help if the large packet remains whole on one task.
Here trip_id identifies a trip and depot names its depot. A per-trip check, such as validating each trip_id, can be shared without gathering every trip from one depot. A depot calculation, such as counting D7 trips, must combine information sharing a grouping key. The kind of work determines whether redistribution helps.
A partition is not automatically a depot in a real Spark plan. Data may be redistributed, partly aggregated and optimized before the result. Our librarian picture explains skewed keys, not the exact number or duration of tasks. For a real job, inspect its plan and metrics instead of treating the drawing as a measurement.
Pause and think
Are a Spark partition and a depot necessarily the same thing?
See the explanation
No. A partition is a data piece for a task; a depot is a column value used here as a key.
Lesson · explanation
Count workloads and find the hot key
The copy has twelve trips for D7. D8, D9 and D10 have two each. Add the four groups: 12 + 2 + 2 + 2 = 18. Depot IDs are grouping labels, not trip numbers. D7 is far more frequent than each other depot in this small dataset.
Sort workloads from small to large: [2, 2, 2, 12]. The median is a typical center. With four numbers, average the two middle values: (2 + 2) ÷ 2 = 2. The maximum is 12. Maximum divided by median is 12 ÷ 2 = 6.
Calling D7 six times the median workload describes this data imbalance. It does not mean a real task will take exactly six times as long. Spark may optimize operations, workers may differ and each row may cost different effort. The ratio 6 tells us to inspect the D7 stage, not to announce a measured runtime.
Imagine four shopping bags: three contain two items, and one has twelve. D7 is the hot key, the value with many more rows. But those twelve items are not duplicate copies just because they share a bag. A trip needs separate evidence of duplication before it can be removed.
Pause and think
What are the total trips and maximum-to-median workload ratio?
See the explanation
There are 18 trips; sorted loads are [2, 2, 2, 12], median 2 and 12 ÷ 2 = 6.
Lesson · explanation
See why grouping creates exchanges
A shuffle moves data between tasks or workers so information that must be combined can meet. Imagine four librarians each holding cards from several depots. To count all D7 cards, they exchange information so D7 contributions can be gathered or partial counts added. Such exchanges may consume network time and resources.
groupBy("depot").count() asks for one result per depot. Its key is the depot value: D7, D8, D9 or D10. All twelve D7 trips contribute to the D7 result. Spark may make partial aggregates before moving data; it does not always send twelve raw rows to one task in every plan.
Our [2, 2, 2, 12] picture shows why a frequent key can be troublesome, but it simplifies execution. Depending on the plan, skew may arise before, during or after grouping. A later join on depot could also amplify D7's cost. Ask which exact stage has uneven task times before choosing a fix.
A counterexample is treating every shuffle as a mistake. If data must be grouped by depot, some exchange is often needed for correct counts. The goal is to understand its cost and choose a plan that retains all eighteen trips. Speed has no value if the result forgets passages.
Pause and think
What can a shuffle do for groupBy("depot")?
See the explanation
It moves or combines same-depot information across tasks to produce a result per key, possibly using network resources.
Lesson · explanation
Read repartition(4, "trip_id") without magical promises
routes.repartition(4, "trip_id") asks Spark to redistribute rows into four partitions using trip identifiers. For independent per-trip work, that may prevent one task from receiving almost everything. If eighteen rows were shared ideally, four piles might hold [5, 5, 4, 4] rows.
That [5, 5, 4, 4] list is an illustration, not guaranteed Spark output. The actual split depends on trip_id values, distribution and plan. repartition itself can cause a shuffle; moving cards costs time. Measure the stage before adding redistribution that might help little or even slow the job.
More importantly, a later step may be groupBy("depot"). Then trips distributed by trip_id must contribute again to groups D7, D8, D9 and D10. Another exchange or key combination can occur. D7 remains the frequent key of twelve trips. A better balanced trip stage does not guarantee an equally balanced depot stage.
Picture students sharing cards evenly for a per-card check, then being asked to build one file per depot. D7 cards spread during checking must still be gathered or counted together. The first success does not remove the later grouping need. Diagnose the two stages separately instead of calling the whole job balanced.
Pause and think
Does repartition(4, "trip_id") guarantee [5, 5, 4, 4] and solve D7?
See the explanation
No. That split is imaginary; per-trip work may improve, but groupBy("depot") still combines D7.
Lesson · explanation
Why partitioning by depot alone is not a cure
One might try repartition(4, "depot"), expecting four partitions for four depots. Yet all rows with key D7 still contribute to the same depot group. Asking for four partitions does not automatically split one hot key into four independent pieces that magically produce a correct final count.
Even if D8, D9 and D10 are separate, D7 has twelve trips against two each for the others. More partitions can create tiny tasks and more movement without removing key skew. It is like adding more desks where a queue of twelve people must still use one particular service window. Desk count alone does not explain the wait.
One possible approach for a hot key is to compute partial counts across several groups and correctly add those counts in a second stage. That needs careful design and verification. Splitting D7 and forgetting to combine pieces would give a wrong answer. Other plans may be better depending on the operation, data size and observed metrics.
The exercise does not run an advanced optimization. It teaches you to ask first whether the slow work is independent per trip or tied to grouping by depot. If cost arises in a shuffle or hot key after groupBy, moving rows at the start may only move the cost. Diagnosis comes before a code change.
Pause and think
Why is repartition(4, "depot") not a guaranteed D7 cure?
See the explanation
D7 remains one grouping key with twelve trips; increasing partitions alone does not remove that concentration.
Lesson · explanation
Measure a real job instead of guessing
In the page's local PySpark lab, by_trip.explain() prints a plan after redistribution by trip_id. Then by_depot.explain() shows the grouping plan. Comparing them helps locate planned exchanges. explain() describes a plan; it does not by itself report each task's real duration or volume.
For an actual execution, inspect metrics for the slow stage: task durations, data read or exchanged, partition sizes and row counts. If three tasks finish quickly and one much later, compare their loads. A long task might also result from a busy machine or another cause, so connect the measurements with the plan.
The lesson's standalone Python script does not run Spark. It adds D7=12 and D8=D9=D10=2, sorts loads and calculates 12/2=6. Its imaginary [5, 5, 4, 4] list merely shows what a better shared independent stage could look like. Do not present that script as a cluster measurement or exact repartition result.
A counterexample is changing several settings together, noticing a faster run and claiming one new partition caused it. Compare one stage before and after, keep data the same and check results. Imani can then tell whether a change truly helps without losing a reproducible account of D7's trips.
Pause and think
How do explain() and execution metrics differ?
See the explanation
explain() shows the plan, while execution metrics show observed task durations and data volumes.
Lesson · explanation
Keep all eighteen trips while optimizing
Mara needs a diagnosis before the fictional meeting. Start with counts: eighteen trips, twelve for D7 and two each for D8, D9 and D10. Our illustrative loads are [2, 2, 2, 12], median 2 and maximum 12, ratio 6. This supports inspecting a D7-related stage instead of deleting rows.
Explain what may change: repartition(4, "trip_id") can better share per-trip work without promising [5, 5, 4, 4]. A later groupBy("depot") must combine D7 contributions again and may recreate skew. Look for this in plans and metrics. Do not treat the four teaching loads as mandatory real Spark partitions.
Every optimized version must preserve the same results: D7=12, D8=2, D9=2, D10=2 and 18 trips total. If D7 is temporarily split, add pieces correctly. A result with seventeen trips might lose Imani's clue; nineteen might invent a passage. Check correctness before celebrating a speedup.
The mission's conclusion has limits: D7 is the hottest key in this copy and may explain an unbalanced stage. That alone does not show which trip led to the hidden shell or the exact cause of a real slowdown. The next lesson explores large-table joins, where a wrong key can make false depot links. Here you protect the facts first.
Pause and think
Which counts must remain after a correct optimization?
See the explanation
D7=12, D8=2, D9=2, D10=2 and 18 trips in total.
Visual guide
The hot D7 key
- 118 trips: D7=12; D8/D9/D10=2
- 2Group by depot: one dominant load of 12
- 3Repartition by trip_id: may spread independent work
- 4groupBy depot: D7 must be gathered again
Changing partitions can move the cost without removing the skewed key.
Code · read each line
Calculate skew on paper
from collections import Counter
from statistics import median
depot_counts = Counter({"D7": 12, "D8": 2, "D9": 2, "D10": 2})
loads_by_depot = sorted(depot_counts.values())
balanced_row_tasks = [5, 5, 4, 4]
print("rows", sum(loads_by_depot))
print("depot_loads", loads_by_depot)
print("largest_to_median", max(loads_by_depot) / median(loads_by_depot))
print("hypothetical_row_tasks", balanced_row_tasks)
print("same_rows", sum(balanced_row_tasks) == sum(loads_by_depot))The standalone script prints 18 rows, loads [2, 2, 2, 12], and a maximum-to-median ratio of 6. [5, 5, 4, 4] is an imaginary balanced scenario for per-trip work, not guaranteed Spark behavior.
Configuration · read the values
Compare two local PySpark plans
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[4]").appName("skew-practice").getOrCreate()
rows = [(f"D7-{i}", "D7") for i in range(12)]
rows += [(f"{depot}-{i}", depot) for depot in ("D8", "D9", "D10") for i in range(2)]
routes = spark.createDataFrame(rows, ["trip_id", "depot"])
by_trip = routes.repartition(4, "trip_id")
by_trip.explain()
by_depot = by_trip.groupBy("depot").count()
by_depot.explain()
print(sorted((r["depot"], r["count"]) for r in by_depot.collect()))
spark.stop()This local code builds 18 trips, repartitions by trip_id, prints a plan, groups by depot, and prints the next plan. Expected counts remain D7=12 and the other three depots at 2. PySpark is needed to run it; this page launches no cluster.
PART 2 · WATCH IT WORK
A complete worked example
Follow each step, then the result
Worked example: four piles
D7 has 12 trips and each of the other three depots has 2.
- Add them: 12 + 2 + 2 + 2 = 18 trips.
- Sort loads: [2, 2, 2, 12]; the median is 2 and the largest is 12.
- Compare 12 ÷ 2 = 6: D7 is the hot key in this example.
- Imagine independent per-trip work on four tasks [5, 5, 4, 4]; then remember groupBy(depot) must combine D7 again.
Repartitioning may balance one stage, while a key-based operation recreates the imbalance.
How this helps with your missionFor Mara and Imani, count 18 trips and measure [2, 2, 2, 12]: median 2, maximum 12, ratio 6. Explain that a shuffle can combine contributions sharing a key and repartition(4, "trip_id") may balance independent work without guaranteeing a cure for D7 grouping. Inspect plans and metrics for the slow stage. Delete no trip without duplicate evidence; results must keep D7=12, D8=D9=D10=2 and total 18.
PART 3 · YOUR TURN
Use the lesson to solve the mission
Story scene · practical task
Mission: the worker that never finishes
The trip map fills up. Three workers finish quickly; a fourth still handles D7 passages. Voss wants to delete 'repeated' trips to accelerate the job, which could erase the lead. Mara asks for a diagnosis without touching originals. The meeting presses the characters, but the exercise has no timer.
Your task
- Calculate total rows and the ratio between maximum and median loads.
- Explain what a shuffle does when grouping by depot.
- Say whether repartitioning by trip_id guarantees that D7 is fixed.
- State the counts that any optimized output must retain.
How to know you have succeeded
- 18 trips; ratio 6.
- Shuffle gathers rows sharing a key.
- No: independent per-trip work may balance, then groupBy gathers D7.
- D7=12, D8=D9=D10=2, total 18.
Try code or SQL and keep a local draft. The mission questions are checked separately below.
See the worked answer
- The 18 rows have loads [12,2,2,2]. Sorted [2,2,2,12], the median is 2 and 12/2=6.
- Shuffle exchanges rows between tasks so rows with the same depot can be combined; network work may increase.
- repartition(4, trip_id) may help independent trip work but promises no exact split, and groupBy(depot) gathers D7 again. Compare plans and metrics.
- Do not remove repeated trips without evidence they are duplicates. The copy must still show 12, 2, 2, and 2 trips, totaling 18.
You can recognize a hot key without deleting its trips. Next you will study large-table joins, where a poor key can create false links to the depot.
Before you leave
Remember this
- Spark divides data into partitions processed by tasks on workers.
- A shuffle exchanges data to combine rows sharing a key; D7 is the frequent key here.
- Illustrative loads [2, 2, 2, 12] have median 2 and maximum 12, giving ratio 6.
repartition(4, "trip_id")may help per-trip work but does not guarantee [5, 5, 4, 4].- A later
groupBy("depot")must combine D7 again and may recreate skew. - Every optimization must retain 18 trips and counts D7=12, D8=2, D9=2, D10=2.
Continue with the integrated lessons
After the lesson and its mission, work through the additional lessons below in order. Each workshop supplies its own fictional data: do not merge identifiers or times from separate exercises into the story timeline.
Part of the lesson · keep nearby
New words, explained
These are the names of ideas used in the lesson above. Return here whenever a word feels unfamiliar.
- Partition
- A piece of data Spark gives to a task.
- Task
- A unit of work processing a partition or a step.
- Shuffle
- Movement of data between tasks, often needed to group by key.
- Key
- A value used to bring rows together, such as depot.
- Skew
- An imbalance where a few keys or partitions have far more rows.
- repartition()
- A Spark operation that changes row distribution and may cause a shuffle.
- Worker
- A process or machine executing distributed tasks.
Approfondissements de ce cours
Choisir une structure selon ses accès et ses transformations
Sur une chaîne sans taille mémorisée, calculer la longueur exige de suivre toutes les cellules jusqu’à None : O(N). On peut conserver une taille dans une enveloppe ou un suffixe immuable, mais cela ajoute des champs, des mises à jour et des invariants. Le PDF oppose ce surcoût à l’usage fréquent de cons ; ce choix dépend du contexte, pas d’une interdiction universelle de mémoriser une longueur.
Pour trouver la cellule d’indice k, on suit k liens depuis la tête ; l’accès arbitraire est linéaire dans le pire cas, contrairement à l’accès constant d’un tableau. Lire la tête reste constant. Ajouter ou retirer à une position arbitraire exige également de retrouver cette position. Random access signifie accès arbitraire : c’est notamment le sens de l’expression Random Access Memory. Le PDF relate un jeu dont presque tout le temps de chargement venait d’accès arbitraires dans une chaîne ; remplacer la chaîne par un tableau changeait le coût dominant. Ces temps historiques ne prédisent pas ceux de notre application.
Concaténer deux tableaux A et B de tailles N et M en un nouveau tableau coûte O(N + M) copies. Sur des chaînes immuables, copier les N cellules de A en les faisant pointer finalement vers B coûte O(N), indépendamment de M ; la queue B est partagée. Le schéma récursif est concat(A, B) = B si A est vide, sinon cons(tête(A), concat(queue(A), B)). Une implémentation Python récursive n’est adaptée qu’aux petites chaînes à cause de la limite de récursion.
Relier directement la dernière cellule mutable de A à B évite les nouvelles cellules mais modifie A. Une autre variable qui désigne A voit désormais la concaténation ; des traitements concurrents peuvent observer une taille devenue périmée. Copier des cellules rend l’opération plus prévisible, sans garantir l’indépendance des objets contenus dans les cellules. Répéter des concaténations de tableaux en recopiant à chaque fois une grande sortie peut provoquer un coût quadratique ; construire par append/extend ou utiliser un flux est souvent plus approprié en Python.
Un filtre conserve les valeurs pour lesquelles un prédicat renvoie vrai. Agrandir un tableau de taille exactement K après chaque valeur conservée implique 0 + 1 + … + K − 1 copies : O(N²) au pire cas. Ajouter en tête d’une chaîne coûte O(N) au total mais inverse l’ordre de sélection, sauf correction. Pour un tableau fixe, compter d’abord les valeurs puis remplir un tableau de taille connue donne O(N), en deux passages. Le prédicat est alors évalué deux fois et les données peuvent changer entre les passages : les effets de bord et la stabilité du résultat comptent.
Une compréhension de liste Python construit directement le résultat et préserve l’ordre de parcours ; elle bénéficie du tableau dynamique. Elle ne suit donc pas la variante historique du tableau agrandi d’une seule case à chaque insertion. Si le prédicat coûte C, le coût du filtre est O(NC), avec O(K) références dans le résultat. Un générateur peut éviter de conserver toute la sortie mais reporte les calculs à la consommation.
La synthèse historique concerne les structures idéales : tableau fixe, accès et taille O(1), ajout avec copie O(N), concaténation O(N + M), filtrage en deux passes O(N) ; chaîne simple, accès arbitraire et taille O(N), ajout en tête O(1), concaténation O(N), filtrage O(N). Elle ne doit pas être appliquée mécaniquement aux classes nommées « liste » ou « tableau » d’un langage.
Convertir une chaîne en tableau puis un tableau en chaîne peut se faire en O(N) en conservant l’ordre. Cela est rentable si une phase de collecte est suivie de nombreux accès par indice ; multiplier les conversions pour quelques opérations peut coûter davantage qu’il ne rapporte. Choisis selon les usages dominants, les bibliothèques disponibles et des mesures. Documente le coût des opérations d’une API : proposer une opération dans l’interface ne signifie pas qu’elle soit efficace.
Exemple appliqué aux données
def vers_liste(chaine):
resultat = []
while chaine is not None:
valeur, chaine = chaine
resultat.append(valeur)
return resultat
def vers_chaine(valeurs):
chaine = None
for valeur in reversed(valeurs):
chaine = (valeur, chaine)
return chaine
assert vers_liste(vers_chaine([3, 8, 5])) == [3, 8, 5]
valides = [x for x in [3, -1, 8] if x >= 0]
assert valides == [3, 8]
def concat_chaine(a, b):
valeurs_a = vers_liste(a)
resultat = b
for valeur in reversed(valeurs_a):
resultat = (valeur, resultat)
return resultat
a = vers_chaine([2, 4])
b = vers_chaine([6, 8])
c = concat_chaine(a, b)
assert vers_liste(c) == [2, 4, 6, 8]
assert vers_liste(a) == [2, 4]
assert c[1][1] is b # suffixe partagé, cellules immuables
Réutilise le modèle de chaîne (valeur, suite) et None de la leçon sur les structures.
À toi de jouer
Explique pourquoi valeurs = valeurs + [x] dans une longue boucle risque de coûter plus cher que valeurs.append(x).
Voir la correction expliquée
La concaténation reconstruit la liste avec toutes les anciennes références à chaque itération : la somme des copies peut être quadratique. append ajoute à la fin du tableau dynamique avec un coût amorti constant. Les deux n’ont pas les mêmes effets sur les références qui désignent l’ancienne liste.
Adaptation en français pour Python 3.12 et les traitements de données ; exemples C, PHP, OCaml et Java transposés en Python. Les coûts annoncés précisent le modèle de données et les hypothèses.
Références : Structures de données Python · Collections et deque · Recherche dichotomique bisect · Guide du tri Python.
Adapté de Algorithmique pour l’apprenti programmeur, bluestorm, Cygal et lastsseldon, pages 25–30. Consulter le PDF source et ses illustrations · Provenance. Creative Commons 2.0 — variante non précisée de façon lisible dans cette copie ; mention de couverture : « Licence Creative Commons 7 2.0 ». Autorisation d’adaptation déclarée par le demandeur.
Chercher par dichotomie et reconnaître un logarithme
Dans un jeu de recherche d’un entier compris entre 1 et 100, tester successivement les nombres peut demander cent essais. Proposer le milieu et éliminer la moitié incompatible réduit beaucoup plus vite les possibilités : sept essais suffisent dans le pire cas. On exclut bien le milieu déjà refusé afin de ne pas recommencer sur le même intervalle.
Le même principe retrouve un identifiant dans un tableau trié : comparer l’élément du milieu, puis continuer uniquement dans la moitié qui peut contenir la cible. Un intervalle vide signifie que la cible est absente. Il faut un ordre cohérent et un accès rapide au milieu. Une chaîne triée peut être parcourue, mais elle ne bénéficie pas du même temps logarithmique si chaque accès au milieu exige de suivre ses liens. Le tri préalable est un coût à compter si les données ne sont pas déjà organisées.
À chaque étape le nombre de candidats est environ divisé par deux. Doubler l’entrée ajoute environ une comparaison : multiplier par 1 024 ajoute environ dix étapes ; multiplier par un milliard en ajoute environ trente. Le logarithme en base 2 exprime cette croissance. Pour une taille entière, le nombre de divisions jusqu’à un est lié à un arrondi du logarithme, ce qui explique les marches du graphique historique.
Les logarithmes de bases fixes supérieures à un ne diffèrent que d’un facteur constant ; le choix de la base ne change donc pas O(log N). C’est une croissance bien plus lente que N ou N². Cela ne rend pas instantanée une opération dont la comparaison ou la lecture distante est très coûteuse ; il faut toujours revenir au modèle de coûts.
Le module bisect fournit des positions d’insertion plutôt qu’un test direct d’égalité. Pour vérifier la présence après bisect_left, il faut contrôler que la position est dans la liste et que la valeur y est égale à la cible. Insérer effectivement dans une list reste linéaire malgré la recherche logarithmique de l’emplacement. La séquence ne doit pas être modifiée pendant la recherche.
Exemple appliqué aux données
def chercher(valeurs, cible):
debut, fin = 0, len(valeurs)
while debut < fin:
milieu = (debut + fin) // 2
if valeurs[milieu] < cible:
debut = milieu + 1
else:
fin = milieu
return debut < len(valeurs) and valeurs[debut] == cible
assert chercher([2, 5, 8, 12], 8)
assert not chercher([], 8)
assert not chercher([2, 5, 8, 12], 7)
Exemple Python 3.12 ; les assertions vérifient les résultats attendus sur ces données de démonstration.
À toi de jouer
Teste une valeur avant la première, après la dernière et plusieurs doublons. Explique l’invariant de l’intervalle.
Voir la correction expliquée
Si la cible existe, une occurrence compatible reste dans l’intervalle recherché. La borne gauche avance au-delà des valeurs strictement plus petites ; la borne droite recule au milieu sinon. Le résultat final est la première position possible ; les vérifications de limite et d’égalité évitent les faux positifs.
Adaptation en français pour Python 3.12 et les traitements de données ; exemples C, PHP, OCaml et Java transposés en Python. Les coûts annoncés précisent le modèle de données et les hypothèses.
Références : Structures de données Python · Collections et deque · Recherche dichotomique bisect · Guide du tri Python.
Adapté de Algorithmique pour l’apprenti programmeur, bluestorm, Cygal et lastsseldon, pages 31–33. Consulter le PDF source et ses illustrations · Provenance. Creative Commons 2.0 — variante non précisée de façon lisible dans cette copie ; mention de couverture : « Licence Creative Commons 7 2.0 ». Autorisation d’adaptation déclarée par le demandeur.
Comparer les coûts des parcours et chercher le plus proche
Sur un arbre fini de N nœuds, DFS et BFS visitent chaque nœud une fois : O(N) temps. Pour le BFS, la file peut contenir une partie de deux couches successives ; sa mémoire est O(L), où L est la largeur maximale d’une couche, en ignorant les résultats conservés par l’appelant. Au pire, une racine ayant N − 1 enfants demande une mémoire linéaire.
Le DFS récursif conserve les appels du chemin courant : O(H) profondeur de pile pour une hauteur H, à condition d’itérer sur les enfants sans matérialiser de gros résultats intermédiaires. Une chaîne de N nœuds donne H = N. Attention : la version itérative qui empile tous les enfants peut garder beaucoup de frères en attente ; sur un arbre général de degré non borné elle peut demander O(N), même quand la hauteur est faible. Le PDF assimile trop rapidement cette pile explicite au seul chemin courant : la distinction est corrigée ici.
Une mesure de mémoire doit préciser si elle inclut la structure d’entrée, les résultats produits et les copies intermédiaires. Une fonction retournant une liste de toutes les valeurs conserve au moins N références de sortie, même si la pile d’appels est petite. Les variantes des noms « hauteur » et « profondeur » ne doivent pas masquer ces dimensions différentes.
Pour compter tous les nœuds ou obtenir toutes les valeurs satisfaisant un prédicat, les deux parcours conviennent. Pour trouver un nœud quelconque satisfaisant une condition, chacun peut s’arrêter au premier trouvé, mais pas forcément au même. Si l’on veut un nœud à distance minimale de la racine dans un arbre à arêtes non pondérées, BFS fournit cette garantie : le premier résultat appartient à la première couche possible. Plusieurs nœuds peuvent être à la même distance.
Dans un catalogue de dossiers, BFS peut ainsi retrouver le premier fichier valide avec le moins de niveaux depuis la racine. DFS peut découvrir d’abord un fichier beaucoup plus profond. Dans un labyrinthe ou un graphe comportant des cycles, il faut en plus mémoriser les nœuds visités ; si les arêtes ont des coûts différents, la garantie de moindre nombre d’arêtes n’est plus une garantie de coût minimal. Les algorithmes de graphes et de files de priorité sont annoncés dans la conclusion historique mais ne sont pas développés dans ce PDF de 2011 : cette adaptation ne leur attribue pas une couverture inexistante.
Exemple appliqué aux données
def plus_proche(racine, accepte):
attente = deque([(racine, 0)])
while attente:
noeud, distance = attente.popleft()
if accepte(noeud):
return noeud.valeur, distance
attente.extend((enfant, distance + 1) for enfant in noeud.enfants)
return None
assert plus_proche(arbre, lambda n: n.valeur in {'clients', 'csv'}) == ('clients', 2)
assert plus_proche(arbre, lambda n: n.valeur == 'absent') is None
Réutilise arbre et deque, présentés dans les leçons précédentes. Les exemples décrivent un arbre fini sans cycle.
À toi de jouer
Dessine une racine avec mille feuilles. Compare la mémoire de DFS récursif, DFS empilant tous les enfants et BFS.
Voir la correction expliquée
La hauteur en nœuds est deux : le DFS récursif qui parcourt les enfants un par un conserve une profondeur constante. La pile explicite empilant toutes les feuilles et la file BFS peuvent chacune conserver environ mille références : O(N). Cet exemple contredit une affirmation générale O(H) pour toutes les versions itératives DFS.
Adaptation en français pour Python 3.12 et les traitements de données ; exemples C, PHP, OCaml et Java transposés en Python. Les coûts annoncés précisent le modèle de données et les hypothèses.
Références : Structures de données Python · Collections et deque · Recherche dichotomique bisect · Guide du tri Python.
Adapté de Algorithmique pour l’apprenti programmeur, bluestorm, Cygal et lastsseldon, pages 69–70. Consulter le PDF source et ses illustrations · Provenance. Creative Commons 2.0 — variante non précisée de façon lisible dans cette copie ; mention de couverture : « Licence Creative Commons 7 2.0 ». Autorisation d’adaptation déclarée par le demandeur.