Corrigés TDs Informatique 1A Agro

Course, Informatique : programmation et bases de données (2026-2027), 2026

Je mettrai ici, au fur et à mesure, les corrections des TD, comme alternative aux corrections d’E-campus et en suivant les consignes que je vous donne en cours.

Pensez à consulter régulièrement cette page !

TD 1 à 4

9.1. Exercise Tranches d’âge

Voir la correction
# 1. Imports section
import random


# 2. Functions section
def age_evaluator_simplified(age):
    """
    This function prints a message depending on the age range
    """
    if 0 < age <= 10:
        return "Vous êtes un enfant"

    elif 17 >= age > 10:
        return "Vous êtes un adolescent"

    elif 64 >= age > 17:
        return "Vous êtes un adulte"

    elif 100 >= age > 64:
        return "Vous êtes un aı̂né"

    else:
        return "Vous avez un problème avec votre génerateur d'age"


# 3. Main routine section
if __name__ == "__main__":
    gerenated_age_1 = random.randint(1, 100)
    gerenated_age_2 = random.randint(1, 100)

    # This time, I save the age groups in variables because we'll use them multiple times.
    age_group_1 = age_evaluator_simplified(gerenated_age_1)
    age_group_2 = age_evaluator_simplified(gerenated_age_2)

    print(f"Vous avez {gerenated_age_1} ans, {age_group_1}")
    print(f"Vous avez {gerenated_age_2} ans, {age_group_2}")
    print(
        "c'est la meme tranche d'âge"
        if age_group_1 == age_group_2
        else "ce ne sont pas les mêmes tranches d'âge"
    )

9.2. Exercise Devine un nombre

Voir la correction
# 1. Imports section
import random

# 2. Functions section
# No functions in this excersise

# 3. Main routine section
if __name__ == "__main__":
    number = random.randint(1, 100)
    print("I have a number in mind. Would you be able to guess it !")
    continue_game = True
    counter = 0

    while continue_game and counter < 7:
        user_entry = input("Tap your guess \n")
        guess = int(user_entry)
        if guess == number:
            print(
                f"Congrats, you guessed the number, it was {number}\n you did it in {counter} tries"
            )
            continue_game = False
        else:
            if guess > number:
                print("Nice try, but that's not the number,")
                print(f"The number I'm thinking on is less than {guess}")
            else:
                print("Nice try, but that's not the number,")
                print(f"The number I'm thinking on is more than {guess}")
            counter += 1
            if counter == 7:
                print("Sorry, your tries are over :c")

9.3. Exercise Les stars

Voir la correction
# 1. Imports section
# It's empty as we don't need any external package on this script


# 2. Functions section
def make_triangle(n: int):
    """
    This function print a triangle of stars by simply printing
    a line of n stars and making n = n-1 for the next iteration.
    """
    for _ in range(n):
        line = n * "*"
        n -= 1
        print(line)


# 3. Main routine section
if __name__ == "__main__":
    base = int(input("Donnez la taille de la base de votre triangle d'étoiles : "))
    make_triangle(base)

9.4. Exercise Tri par insertion

Voir la correction
# 1. Imports section
# It's empty for now, as we don't need any external package on this script


# 2. Functions section
def insere(liste, elem):
    """
    Fonction qui inset un élement à sa bonne place dans une liste.
    """
    # First of all, we search the position for insering the element.
    i = 0
    while i < len(liste) and liste[i] < elem :
        i +=1
    # We insert elem in i position if it is not the last of the list
    if i < len(liste) :
        liste.insert(i,elem)
    # We insert elem at the end if it is the bigger element into the list
    else:
        liste.append(elem)

    return liste


def tri_par_insertion(liste):
    """
    Fonction qui trie une liste par insertion
    """
    liste_triee = []
    for el in liste :
        liste_triee = insere(liste_triee, el)
    return liste_triee

# 3. Main routine section
if __name__ == "__main__":
    print(insere([1,2,4,5,6,9,10], 11))
    print(tri_par_insertion([10,9,8,7,3,12,13,5,4,1,11,14,2]))

9.5. Exercise Listes enterlacées

Voir la correction
# 1. Imports section
# It's empty for now, as we don't need any external package on this script

# 2. Functions section
def entrelacer_insertion(liste_1, liste_2):
    """
    Fonction qui inset un élement à sa bonne place dans une liste.
    """
    if len(liste_1) == len(liste_2):
        # First of all, we search the position for insering the element.
        liste_entrelacee = []
        for i,j in zip(liste_1, liste_2):
            liste_entrelacee.extend([i,j])
        return liste_entrelacee

    return "List are not of the same length, provide to list of the same length."


# 3. Main routine section
if __name__ == "__main__":
    print(entrelacer_insertion([1,2,3],["A","B","C"]))

10.3. Exercise fichiers

Voir la correction
# 1. Imports section
# It's empty as we don't need any external package on this script


# 2. Functions section

def compte_nb_lignes(nom_fichier):
    """
    Read a file and print the number of lines it has
    """
    mon_fichier = open(nom_fichier, "r", encoding="utf-8")
    liste_lignes = mon_fichier.readlines()
    mon_fichier.close()
    print(len(liste_lignes))

def affiche_no_ligne(nom_fichier):
    """
    Read a file and print each line alongside its line number
    """
    mon_fichier = open(nom_fichier, "r", encoding="utf-8")
    liste_lignes = mon_fichier.readlines()
    mon_fichier.close()
    for i, ligne in enumerate(liste_lignes):
        print(f"{i} : {ligne[:-1]}")

def decoupe_split(nom_fichier):
    """
    Read a file and print a list for each line, where each list element is a word
    """
    mon_fichier = open(nom_fichier, "r", encoding="utf-8")
    liste_lignes = mon_fichier.readlines()
    mon_fichier.close()
    for ligne in liste_lignes:
        print(ligne.split())

def decoupe_algo(nom_fichier):
    """
    As `decoupe_algo` but without using the `.split()` method
    """
    mon_fichier = open(nom_fichier, "r", encoding="utf-8")
    liste_lignes = mon_fichier.readlines()
    mon_fichier.close()
    for ligne in liste_lignes:
        L=[]
        mot=""
        for caratere in ligne:
            if caratere != " ":
                mot += caratere
            else:
                L.append(mot)
                mot=""
        L.append(mot[:-1])
        print(L)

# 3. Main routine section
if __name__ == "__main__":
    compte_nb_lignes("fable.txt")
    affiche_no_ligne("fable.txt")
    decoupe_split("fable_copie.txt")
    decoupe_algo("fable.txt")

Pour les éleves avancés

Vous maîtrisez la programmation en Python. Vous avez réalisé au moins tous les exercices obligatoires des TDs 1,2,3 et 4. Je vous propose de programmer un petit « grep ».

Voir l'exercise

Build a Tiny grep

In this exercise, you will build a small text-search utility.

The goal is not to reproduce the full Unix grep command (https://man7.org/linux/man-pages/man1/grep.1.html), but to implement a few interesting features yourself.

Develop your tool in the same directory where you should place the test file available here.


The actual task consist on implementing the following function :

find_matches(filename, pattern)

It should search a text file and return every line matching a pattern.

For each match, return:

(line_number, line)

For example, given the file:

INFO: Starting server
INFO: Loading configuration
ERROR: connection timeout
INFO: Retrying...
ERROR: request timeout!
INFO: Server stopped

this call:

find_matches("log.txt", "ERROR:*timeout?")

should find:

[
    (3, "ERROR: connection timeout"),
    (5, "ERROR: request timeout!")
]

Your solution should not repeatedly scan the pattern or text from the beginning unnecessarily.

Think about the algorithm before writing lots of code.


Pattern Syntax

You must not use regular expressions.

Instead, take the following special characters into account during implementation:

PatternMeaning
*Matches zero or more characters
?Matches exactly one character

All other characters match themselves.

Examples

matches("hello", "hello")
# True

matches("hello", "h?llo")
# True

matches("hello", "h*")
# True

matches("hello", "*ell*")
# True

matches("hello world", "h*world")
# True

matches("hello", "h?ll")
# False

matches("hello", "bye*")
# False

Requirements

Your implementation must:

  1. Process the file line by line. Do not load the entire file into memory.

  2. Implement the pattern matching yourself (re, fnmatch and glob or any other external library that performs the matching are not allowed).

  3. Line numbers start at 1.


Test Cases

Your implementation should handle at least these cases:

assert matches("hello", "hello")
assert matches("hello", "h?llo")
assert matches("hello", "h*")
assert matches("hello", "*")
assert matches("hello", "*ell*")
assert matches("hello world", "h*world")

assert not matches("hello", "h?ll")
assert not matches("hello", "bye*")
assert not matches("hello", "hello?")
assert not matches("", "?")

Also test:

matches("", "")
matches("", "*")
matches("abc", "***")
matches("abc", "a*c")
matches("abc", "a**c")

⭐ Bonus — Add Case-Insensitive Matching

Add an optional parameter:

find_matches(filename, pattern, ignore_case=False)

For example:

find_matches("log.txt", "error:*", ignore_case=True)

should match:

ERROR: connection timeout
Error: disk full
error: invalid request