← Complete program

Chapter 2 · Course 2 c02-m02

What is an algorithm?

Your goal Write steps precise enough for another person to reach the same result and know when to stop.

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.

01

Story · optional context

The story so far

You are a new hire at Aster Motors, where the team is preparing the Noctis 01 prototype. Two sheets give different instructions for counting checked parts before a test. Mara Sol asks you to write a method everyone can follow in the same way. A computer can come later; today, paper and pencil are enough.

You can open this course directly. You need no earlier episode or knowledge of Python.

02

Before the lesson

Purpose of this course

Write steps precise enough for another person to reach the same result and know when to stop.

Topics covered

Recognize input, steps, result, and stopping condition in an algorithm.; Explain how changing the order of steps can change a result.; Replace a vague instruction with actions someone can check.; Try a method on a small example and on a case that might fool it.

What you will learn

  • Recognize input, steps, result, and stopping condition in an algorithm.
  • Explain how changing the order of steps can change a result.
  • Replace a vague instruction with actions someone can check.
  • Try a method on a small example and on a case that might fool it.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

An algorithm is a method, even without a computer

An algorithm is a series of steps precise enough to answer a question. You already use methods like this: following a recipe, looking for a name on a list, or arranging cards by number. A computer can carry out an algorithm, but the method exists before the code. For this lesson, paper and a pencil are enough.

Imagine Mara telling two people to count the sensors that are ready. One counts every sensor received; the other counts only sensors that were tested. Their answers differ because ready was never defined. A reliable method must say what information it starts with, what to check, and which answer to produce.

An algorithm is not magic. It cannot turn a missing check record into evidence. If no test is recorded for a sensor, the method should say unconfirmed or ask someone to investigate. A good method can show its limits even when every step has been followed correctly.

To write your first algorithm, ask four simple questions: what are the inputs, what happens to each one, when is the work finished, and what result should be announced? They give the method a beginning, a path, and an end. Then another person can try it without guessing what you intended.

Pause and think

Is check the cards and say if everything is fine a precise enough algorithm for Noor?

See the explanation

No. It does not say which cards to read, what check to perform, when to stop, or what result to report.

2

Lesson · explanation

Choose the exact inputs and the expected result

Inputs are the information given to the method at the start. To count checks, the inputs are the cards you must examine. If Mara hands you four cards, name all four. A card marked received might be excluded from the final count after you inspect it, but it must not silently disappear as though nobody looked at it.

The result must answer a clear question. How many different sensors have a confirmed test is not the same as how many cards are in my hand. The mission has four cards but only two distinct sensors with confirmed tests. Without a clear result, a counter may answer the wrong question perfectly.

Picture a box with red and blue marbles. If you are asked for the number of red marbles, counting every marble is easy but useless. First state which marbles are in the box and what kind of answer you need. Only then choose steps that will produce that answer.

A method can use a counter to hold a running total. Set it to zero before reading the first card: at that moment, no card has yet been confirmed as tested by this process. The zero describes the beginning of the calculation, not a conclusion about every sensor in the workshop. It may change as cards meet the rule.

Pause and think

Are S1, S2, S3, and S3-copy all inputs even though the mission's answer is two?

See the explanation

Yes. Examine all four inputs. The counting rule excludes S2 and the copy from the total, but both cards are still read.

3

Lesson · explanation

Write steps another person can repeat

A step is an action clear enough to carry out without guessing. Look at the card is still vague: what should Noor look at? Read its identifier and then read whether it says tested or received is more precise. Two people following the same clear instruction are more likely to reach the same answer.

For each card, keep a short list of identifiers already seen. If an identifier is new, record it. Then, if the card confirms a test, increase the counter by one. If the card says only received, leave the counter alone. If its identifier was already seen, check whether it is a copy before deciding not to count it again.

Imagine tickets at a concert. A visitor may show two photographs of one ticket, but they have only one seat. The ticket number helps you recognize the copy. In the mission, S3-copy has the same identifier as S3. Counting it twice would be like giving two seats to one ticket number.

The method should also say what happens when an identifier is missing or damaged. Set that card aside and ask for confirmation. Do not guess that it is new or quietly throw it away. A step for unusual cases makes the method more useful in a real workshop.

Pause and think

Which instruction is clearer: count the good cards, or read the identifier and add one if it is new and the card says tested?

See the explanation

The second. It names the field to read, the condition to check, and the moment to change the counter.

4

Lesson · explanation

The order of actions can change the final number

A method follows an order. If you increase the counter before reading the status, you will count a card that says only received. If you increase it before checking the identifier, you may count a copy. Doing the right actions in the wrong order does not always give the right answer.

For this problem, read one card, inspect its identifier, check whether that identifier has already been handled, and then read its status before deciding whether to increase the counter. Afterward move to the next card. Keep a copy as evidence, but do not add it again to the total.

Think of a recipe that tells you to bake a cake before mixing the ingredients. Both actions belong in the recipe, but swapping them ruins it. In an algorithm, a check placed after the calculation may arrive too late: the reported total has already been inflated. Try the order on a small example before handing the method to Noor.

The lesson's A, B, and C example is small enough to trace. A is received only, while B and C are checked. The counter begins at zero, stays zero after A, becomes one after B, and becomes two after C. Following the counter one step at a time reveals exactly where a bad method would add an extra one.

Pause and think

If you count S3-copy before checking its identifier, which false total might you report?

See the explanation

You might say three rather than two distinct tested sensors, because S3 and its copy would both increase the counter.

5

Lesson · explanation

Say when to stop and what to report

A stopping condition is the rule that says the work is finished. Here you stop after examining each of the four cards once. Without such a rule, one person might report too early, before the last card, while another might reread cards forever and risk counting them again.

The ending must also say how to report the answer. Saying only two is not enough. Say two distinct sensors with a confirmed test: S1 and S3. This sentence repeats the question and shows which cards support the result. S2 and S3-copy are not hidden; explain why they do not increase the counter.

A loop is a way to repeat the same steps for each card. You do not need to know the code for loops today. Imagine a person taking one card, applying the rule, and repeating while another unread card remains. In a later chapter, a program will perform this kind of repetition using written instructions.

Four cards at the start mean the method should finish after four passes. The final counter may be smaller than four because not every input meets the counting condition. Keep the number of cards examined separate from the number of sensors confirmed as tested.

Pause and think

Why would stop as soon as you find two tested sensors be a poor stopping condition?

See the explanation

You must still read every card. A remaining card could reveal another sensor or an error; the answer you hope for must not decide when checking stops.

6

Lesson · explanation

Test the method with an ordinary case and a tricky one

Testing an algorithm means trying its steps on inputs whose expected answer you know. Begin with the easy case: A received, B checked, C checked. You should get two. If another reader gets three, find the step that counted a receipt as a check. The mistake shows where an instruction was unclear.

Next try a case that might fool the method: a copied card, an unreadable card, or an empty pile. S3-copy tests whether the identifier rule prevents double counting. An unreadable card should lead to a request for confirmation rather than a guess. An empty pile can yield zero confirmed cards among those examined; it does not prove that no sensors exist anywhere in the workshop.

Now trace the mission's four cards by hand. S1 is new and tested: counter one. S2 is new but only received: still one. S3 is new and tested: counter two. S3-copy repeats S3: still two. No cards remain, so the stopping condition has been met. Noor can repeat these exact steps without you.

If Noor gets another total, do not simply say that she is wrong. Replay the steps together and find the first card where your counters differ. A clear method helps find and fix errors. That is one reason engineers write down the steps before asking a computer to repeat them very quickly.

Pause and think

Which case best shows whether your method avoids duplicates: three different cards, or S3 followed by S3-copy?

See the explanation

S3 followed by its copy. A method that counts both fails exactly where the duplicate rule is needed.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: count the checks

Today's cards are A “battery received,” B “battery tested,” and C “battery tested.” The question is “how many batteries are confirmed as tested?”

  1. Input: A, B, and C. Set the count to 0.
  2. Read A: “received” is not “tested.” The count stays 0.
  3. Read B: it says “tested.” The count becomes 1.
  4. Read C: it says “tested.” The count becomes 2.
  5. Stop after all three cards. Result: 2 tested batteries.
What this shows

Anyone can repeat these steps. The answer 2 comes from a clear method, not a guess.

How this helps with your mission

The A, B, C example shows how to start a counter, read every card, leave out a mere receipt, and stop after the last input. In the mission, repeat those steps and add the identifier check so S3-copy is not counted twice. Explain the answer of two to Noor one card at a time: S1 and S3 are distinct and tested, S2 was only received, and the copy is not another sensor.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: write Mara's recipe

The Noctis 01 test is approaching in the story. Mara has four sensor cards: S1 “tested,” S2 “received,” S3 “tested,” and S3-copy “tested.” The last card is a photocopy of S3 with the same identifier. She wants instructions Noor can follow while you are away to report how many different sensors were tested.

Your task

  1. List the input cards and set a starting count.
  2. Describe, in order, how to check each card's identifier and “tested” label.
  3. Write a clear stopping condition.
  4. Follow your method and explain what happens to S2 and S3-copy.

How to know you have succeeded

  • You use four cards and start at 0.
  • You do not count an identifier twice, and count only cards marked “tested.”
  • You stop after checking every card once.
  • You get 2: S1 and S3. S2 was only received; S3-copy is not another sensor.
Open this mission in the browser workspace

Try code or SQL and keep a local draft. The mission questions are checked separately below.

Check the facts in your mission

Answer each factual question, then write your report in your own words. The program checks the choices; compare the report with the worked answer below.

1. Which cards must the method examine at the start?
2. Which rule avoids counting a copy or a mere receipt?
3. When should the method stop?
4. What result should Noor report, and why?
See the worked answer
  1. Input: S1, S2, S3, S3-copy. Set count to 0 and keep a list of seen identifiers.
  2. For each card, read its identifier. If already seen, do not count it again. Otherwise record it and add 1 if the card says “tested.”
  3. Stop after the fourth card, when none remain.
  4. S1 adds 1, S2 adds 0, S3 adds 1, S3-copy adds 0. Result: 2 different tested sensors.

A person can follow this recipe. Next, you will see what changes when instructions are written for a machine.

Before you leave

Remember this

  • An algorithm is a precise method that can be followed on paper before it becomes code.
  • Define the inputs and the question the result must answer.
  • Write repeatable steps in an order that prevents double counting.
  • A stopping condition says when all the inputs have been examined.
  • Test an easy case and a tricky case; never guess missing information.

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.

A–Z

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.

Algorithm
A method made of precise steps in a chosen order to answer a question.
Input
What the method starts with, such as three check cards.
Step
One clear action, such as reading a card or increasing a count.
Result
The final answer, such as “two parts checked.”
Stopping condition
The rule that says when the work is over, such as “after the last card.”

Décrire un algorithme et choisir son organisation de données

Un algorithme décrit une méthode précise permettant de résoudre un problème à partir de conditions initiales. Une recette, une procédure de réception de fichiers ou le calcul d’un indicateur suivent ce principe. « Charger le fichier » suppose un fichier accessible, un format connu et un outil capable de le lire : les préconditions font partie du problème. Le niveau de détail dépend des opérations déjà comprises par la personne ou le programme qui exécutera la procédure.

L’implémentation est la traduction de cette méthode dans un langage. Deux programmes Python peuvent appliquer la même méthode tout en différant dans leurs détails. Les ordinateurs exécutent rapidement des tâches répétitives sans se lasser ; ils servent à rechercher, comparer, analyser, classer ou extraire de l’information. Un calcul réalisable à la main sur dix éléments devient pénible sur un million. Leur rapidité ne compense toutefois pas toujours une méthode dont le travail augmente trop vite.

Une structure de données organise les informations conservées en mémoire. Un catalogue alphabétique permet une recherche différente de celle d’un catalogue désordonné ; y ajouter une entrée exige de préserver l’organisation choisie. Algorithme et structure se choisissent donc ensemble. Avant d’optimiser un pipeline, formule les opérations requises : parcourir chaque reçu, retrouver une référence, ajouter un lot ou extraire le prochain travail.

Le PDF historique « Algorithmique pour l’apprenti programmeur », de bluestorm, Cygal et lastsseldon, mis à jour le 10 août 2011, vise des lecteurs connaissant variables, conditions, boucles et fonctions ; la récursivité est utile pour les chapitres avancés. Ici, les premières définitions apparaissent avant Python et les implémentations détaillées après ces prérequis. Les notions de puissance puis de logarithme sont expliquées lors de leur emploi. Le texte historique annonce aussi des chapitres futurs : nous distinguons ses développements présents de ses promesses non publiées. Son historique de corrections et son sommaire restent consultables dans le PDF source.

Exemple appliqué aux données

etapes = ['vérifier le format', 'lire les lignes', 'valider les champs', 'produire le rapport']
for numero, etape in enumerate(etapes, 1):
    print(numero, etape)

Exemple Python 3.12 ; les assertions vérifient les résultats attendus sur ces données de démonstration.

À toi de jouer

Décris une méthode pour compter les lignes valides d’un fichier et précise ses préconditions.

Voir la correction expliquée

Préconditions : fichier accessible, encodage et séparateur connus, règle de validité explicite. Initialiser le compteur, lire chaque ligne, vérifier les champs puis incrémenter uniquement si la règle est satisfaite. Définir aussi le résultat pour un fichier vide et le traitement d’une ligne illisible.

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 1–8. 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.