Practical activity

Duration1h15

Présentation & objectifs

Voici une liste d’exercices pour expérimenter la construction d’algorithmes en se concentrant sur la construction de boucles. Le sujet porte sur la manipulation des chaînes de caractères. À l’instar des listes/tableaux, les chaînes peuvent être parcourues, et peuvent être vues comme une collection de caractères.

Une fois vos algorithmes conçus, il est recommandé de les coder en Python afin de pouvoir les tester. Cependant, si vous ne vous sentez pas encore à l’aise avec Python, vous pouvez simplement les écrire sur une feuille et les tester à la main.

Lors du test de vos algorithmes, essayez de penser à des cas couvrant tous les résultats possibles. Par exemple, si votre algorithme doit retourner true ou false, testez-le avec des entrées qui conduisent aux deux cas.

Contrainte – Il existe de nombreuses façons d’écrire un algorithme pour résoudre un problème, et de nombreuses façons de programmer un algorithme. Dans cette activité pratique, vous n’avez pas le droit d’utiliser le mot-clé break. Réfléchissez également soigneusement à savoir si vous avez besoin d’une boucle bornée (for) ou non bornée (while).

Important

Le but de cette séance est de vous aider à maîtriser des notions importantes en informatique. Un assistant de programmation intelligent tel que GitHub Copilot, que vous avez peut-être déjà installé, sera capable de vous fournir une solution à ces exercices uniquement à partir d’un nom de fichier judicieusement choisi.

Pour l’entraînement, nous vous conseillons de désactiver ces outils dans un premier temps.

À la fin de l’activité pratique, nous vous suggérons de retravailler les exercices avec ces outils activés. Suivre ces deux étapes améliorera vos compétences à la fois de manière fondamentale et pratique.

Nous vous fournissons également les solutions aux exercices. Veillez à ne les consulter qu’après avoir trouvé une solution, afin de comparer ! Même si vous êtes sûr que votre solution est correcte, jetez-y un œil, car elles fournissent parfois des éléments supplémentaires que vous auriez pu manquer.

Contenu de l’activité

1 — Dernière occurrence

Commencez avec le programme suivant :

# The string to manipulate
s = "IMT Atlantique"
print(s)

# Write your codes here
# ...
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // Write your codes here
        // ...
    }

}

Concevez un algorithme qui détermine la position (entre 0 et la longueur de s moins 1) de la dernière occurrence d’un symbole dans la chaîne s. Le symbole recherché est stocké dans une variable nommée v. L’algorithme affiche la position trouvée ou indique si le symbole n’est pas présent dans s.

L’algorithme peut être évalué avec les valeurs suivantes :

  • s = "IMT Atlantique" et v = 'l'
  • s = "IMT Atlantique" et v = 'z'
  • s = "I love Computer Science and Algorithms" et v = 'o'
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
v = 't'

# Last occurrence of v in s
index = len(s) - 1
while index >= 0 and s[index] != v:
    index -= 1

# Print result
if index >= 0:
    print("Found at index", index)
else:
    print("Not found")
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
v = 'l'

# Use string method to find last occurrence
result = s.rfind(v)

# Print result
if result != -1:
    print("Found at index", result)
else:
    print("Not found")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        char v = 't';

        // Last occurrence of v in s
        int index = s.length() - 1;
        while (index >= 0 && s.charAt(index) != v) {
            index--;
        }

        // Print result
        if (index >= 0) {
            System.out.println("Found at index " + index);
        } else {
            System.out.println("Not found");
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        char v = 'l';

        // Use string method to find last occurrence
        int result = s.lastIndexOf(v);

        // Print result
        if (result != -1) {
            System.out.println("Found at index " + result);
        } else {
            System.out.println("Not found");
        }
    }

}

2 — Première occurrence

Reprenez le même code de base que dans l’exercice 1.

Concevez un algorithme qui détermine la position (entre 0 et la longueur de s moins 1) de la première occurrence d’un symbole dans la chaîne s. Le symbole recherché est stocké dans une variable nommée v. L’algorithme affiche la position trouvée ou indique si le symbole n’est pas présent dans s.

L’algorithme peut être évalué avec les valeurs suivantes :

  • s = "IMT Atlantique" et v = 'l'
  • s = "IMT Atlantique" et v = 'z'
  • s = "I love Computer Science and Algorithms" et v = 'o'
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
v = 't'

# Initialize variable for the while loop
index = 0

# Iterate from the start to the end
while index < len(s) and s[index] != v:
    index += 1

# Print the result
if index < len(s):
    print("Found at index", index)
else:
    print("Not found")
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
v = 'l'

# Use string method to find first occurrence
result = s.find(v)

# Print result
if result != -1:
    print("Found at index", result)
else:
    print("Not found")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        char v = 'l';

        // Initialize variable for the while loop
        int index = 0;

        // Iterate from the start to the end
        while (index < s.length() && s.charAt(index) != v) {
            index++;
        }

        // Print the result
        if (index < s.length()) {
            System.out.println("Found at index " + index);
        } else {
            System.out.println("Not found");
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        char v = 'l';

        // Use string method to find first occurrence
        int result = s.indexOf(v);

        // Print result
        if (result != -1) {
            System.out.println("Found at index " + result);
        } else {
            System.out.println("Not found");
        }
    }

}

3 — Préfixe

Reprenez le même code de base que dans l’exercice 1.

Considérant un second tableau de caractères, nommé pref par exemple, déterminez si pref est un préfixe de s. Réfléchissez bien aux différents scénarios possibles liés aux longueurs de s et pref. L’algorithme affiche si pref est un préfixe de s.

L’algorithme peut être évalué avec les valeurs suivantes :

  • s = "IMT Atlantique" et pref = "IMT"
  • s = "IMT Atlantique" et pref = "IMT Atlantique is a great school"
  • s = "I love Computer Science and Algorithms" et pref = "I love"
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
pref = "IMT"

# Iterate over the string util a different character is found
i = 0
while i < len(s) and i < len(pref) and s[i] == pref[i]:
    i += 1

# Print result
if i == len(pref):
    print(pref, "is a prefix of", s)
else:
    print(pref, "is not a prefix of", s)
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
pref = "IMT"

# Use string method for that
if s.startswith(pref):
    print(pref, "is a prefix of", s)
else:
    print(pref, "is not a prefix of", s)
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The prefix to search
        String pref = "IMT";

        // Iterate over the string until a different character is found
        int i = 0;
        while (i < s.length() && i < pref.length() && s.charAt(i) == pref.charAt(i)) {
            i++;
        }

        // Print result
        if (i == pref.length()) {
            System.out.println(pref + " is a prefix of " + s);
        } else {
            System.out.println(pref + " is not a prefix of " + s);
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        String pref = "IMT";

        // Use string method for that
        if (s.startsWith(pref)) {
            System.out.println(pref + " is a prefix of " + s);
        } else {
            System.out.println(pref + " is not a prefix of " + s);
        }
    }

}

4 — Contient

Reprenez le même code de base que dans l’exercice 1.

Considérant un second tableau de caractères, nommé substr par exemple, déterminez si substr est présent dans s. L’algorithme indique la position de la première occurrence de substr dans s ou s’il n’est pas présent.

L’algorithme peut être évalué avec les valeurs suivantes :

  • s = "IMT Atlantique" et substr = "Atlan"
  • s = "IMT Atlantique" et substr = "Pyhton"
  • s = "I love Computer Science and Algorithms" et substr = "and"
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
substr = "Atlan"

# Initialize variables
index_start = 0
index_sub = 0
found = False

# Outer loop: iterate through each position in the string where the substring could start
while index_start <= len(s) - len(substr) and index_sub < len(substr):

    # Inner loop: check if the substring matches at this position
    index_sub = 0
    while index_sub < len(substr) and s[index_start + index_sub] == substr[index_sub]:
        index_sub += 1
    index_start += 1

# Print a message if not found
if index_sub >= len(substr):
    print("Substring found at position", index_start - 1)
else:
    print("Substring not found")
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
substr = "Atlan"

# You can directly check with 'in' keyword
if substr in s:
    print("Substring found at index", s.index(substr))
else:
    print("Substring not found")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        String substr = "Atlan";

        // Initialize variables
        int indexStart = 0;
        int indexSub = 0;
        boolean found = false;

        // Outer loop: iterate through each position in the string where the substring could start
        while (indexStart <= s.length() - substr.length() && indexSub < substr.length()) {

            // Inner loop: check if the substring matches at this position
            indexSub = 0;
            while (indexSub < substr.length() && s.charAt(indexStart + indexSub) == substr.charAt(indexSub)) {
                indexSub++;
            }
            indexStart++;
        }

        // Print a message if not found
        if (indexSub >= substr.length()) {
            System.out.println("Substring found at position " + (indexStart - 1));
        } else {
            System.out.println("Substring not found");
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        String substr = "Atlan";

        // Use string method for that
        if (s.contains(substr)) {
            System.out.println("Substring found at index " + s.indexOf(substr));
        } else {
            System.out.println("Substring not found");
        }
    }

}

5 — Inverser

Reprenez le même code de base que dans l’exercice 1.

Déterminez un algorithme qui inverse le contenu de la chaîne s.

L’algorithme peut être évalué avec les valeurs suivantes :

  • s = "IMT Atlantique"
  • s = "euqitnaltA TMI"
  • s = "I love Computer Science and Algorithms"
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# Loop to append to a new string
result = ""
for character in s:
    result = character + result

# Print the result
print("Reversed string:", result)
# The string to manipulate
s = "IMT Atlantique"
print(s)

# Using operator []
result = s[::-1]

# Print the result
print("Reversed string:", result)
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // Loop to append to a new string
        String result = "";
        for (int i = 0; i < s.length(); i++) {
            result = s.charAt(i) + result;
        }

        // Print the result
        System.out.println("Reversed string: " + result);
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // Using StringBuilder for reversing a string
        String result = new StringBuilder(s).reverse().toString();

        // Print the result
        System.out.println("Reversed string: " + result);
    }

}

6 — Palindrome

Un palindrome est un mot qui peut se lire dans les deux sens, comme par exemple “radar” ou “laval”. Déterminez une première stratégie naïve pour vérifier si une chaîne est un palindrome basée sur l’algorithme d’inversion conçu précédemment.

L’algorithme peut être évalué avec les valeurs suivantes :

  • s = "laval"
  • s = "rennes"
  • s = "detartrated"
Correction
# Initialize variables
s = "LAVAL"
i = 0

# Iterate over the string
while i < len(s) / 2 and s[i] == s[len(s) - 1 - i]:
    i += 1

# Show result
# Show result
if i >= len(s) / 2:
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")
# The string to manipulate
s = "laval"
print(s)

# Check if s is a palindrome
if s == s[::-1]:
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "laval";
        System.out.println(s);

        // Initialize variables
        int i = 0;

        // Loop to check characters from start and end
        while (i < s.length() / 2 && s.charAt(i) == s.charAt(s.length() - i - 1)) {
          
            i++;
        }

        // Print a message based on the result
        if (i >= s.length() / 2) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }
}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "laval";
        System.out.println(s);

        // Check if s is a palindrome using StringBuilder
        if (s.equals(new StringBuilder(s).reverse().toString())) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }

}

6.1 — Défi supplémentaire (optionnel)

Un palindrome peut aussi être une phrase, telle que "A man, a plan, a canal: Panama". Adaptez votre algorithme pour ignorer les espaces, les signes de ponctuation et convertir en minuscules avant de vérifier si la chaîne est un palindrome.

Python fournit des méthodes intégrées pour ces opérations : isalnum(), lower().

Correction
# The string to manipulate
s = "A man, a plan, a canal: Panama"
print(s)

# Remove spaces, punctuation marks and convert to lowercase
simplified_s = ""
for character in s:
    if character.isalnum():
        simplified_s += character.lower()

# Iterate over the string
i = 0
while i < len(simplified_s) / 2 and simplified_s[i] == simplified_s[len(simplified_s) - 1 - i]:
    i += 1

# Show result
if i >= len(simplified_s) / 2:
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")
# The string to manipulate
s = "A man, a plan, a canal: Panama"
print(s)

# Remove spaces, punctuation marks and convert to lowercase
simplified_s = ''.join(character for character in s if character.isalnum()).lower()

# Check if s is a palindrome
if simplified_s == simplified_s[::-1]:
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "A man, a plan, a canal: Panama";
        System.out.println(s);

        // Remove spaces, punctuation marks and convert to lowercase
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char character = s.charAt(i);
            if (Character.isLetterOrDigit(character)) {
                builder.append(Character.toLowerCase(character));
            }
        }
        String simplifiedS = builder.toString();

        // Iterate over the string
        int i = 0;
        while (i < simplifiedS.length() / 2 && simplifiedS.charAt(i) == simplifiedS.charAt(simplifiedS.length() - 1 - i)) {
            i++;
        }

        // Show result
        if (i >= simplifiedS.length() / 2) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "A man, a plan, a canal: Panama";
        System.out.println(s);

        // Remove spaces, punctuation marks and convert to lowercase
        String simplifiedS = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

        // Check if s is a palindrome using StringBuilder
        if (simplifiedS.contentEquals(new StringBuilder(simplifiedS).reverse())) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }

}

7 — Optimisez vos solutions

Ce que vous pouvez faire maintenant est d’utiliser des outils d’IA tels que GitHub Copilot ou ChatGPT, soit pour générer la solution, soit pour améliorer la première solution que vous avez proposée ! Essayez cela pour tous les exercices ci-dessus, afin de voir les différences avec vos solutions.

Pour aller plus loin

8 — Hexadécimal

Considérez une chaîne représentant un nombre en format hexadécimal. Calculez sa valeur décimale.

Pour rappel, un nombre hexadécimal peut contenir les chiffres suivants : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. ‘A’ vaut 10, et ainsi de suite. Par exemple :

$$\text{8EA4} = 4 * 16^0 + 10 * 16^1 + 14 * 16^2 +8 * 16 ^3$$

Une solution intégrée existe en Python (et dans d’autres langages) pour résoudre ce problème, mais essayez de travailler avec des boucles pour vous familiariser avec leur utilisation. On suppose que chaque symbole dans la chaîne à convertir est un chiffre acceptable en format hexadécimal.

Correction
# Initialize variables
to_convert = "8EA4"
result = 0

# Iterate over the string
for index in range(len(to_convert)):

    # Convert to decimal
    value = None
    match to_convert[index]:
        case 'A': value = 10
        case 'B': value = 11
        case 'C': value = 12
        case 'D': value = 13
        case 'E': value = 14
        case 'F': value = 15
        case  _ : value = int(to_convert[index])
    
    # Aggregate to solution
    power = len(to_convert) - index - 1
    result += 16 ** power * value

# Print result
print("Decimal version of", to_convert, "is", result)
# Value to convert
to_convert = "8EA4"

# Convert into decimal
result = int(to_convert, 16)
print("Decimal version of", to_convert, "is", result)
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // Initialize variables
        String toConvert = "8EA4";
        int result = 0;

        // Iterate over the string
        for (int index = 0; index < toConvert.length(); index++) {

            // Convert to decimal
            int value;
            char currentChar = toConvert.charAt(index);
            switch (currentChar) {
                case 'A': value = 10; break;
                case 'B': value = 11; break;
                case 'C': value = 12; break;
                case 'D': value = 13; break;
                case 'E': value = 14; break;
                case 'F': value = 15; break;
                default: value = Character.getNumericValue(currentChar); break;
            }

            // Aggregate to solution
            int power = toConvert.length() - index - 1;
            result += Math.pow(16, power) * value;
        }

        // Print result
        System.out.println("Decimal version of " + toConvert + " is " + result);
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // Value to convert
        String toConvert = "8EA4";

        // Convert into decimal using Java's built-in method
        int result = Integer.parseInt(toConvert, 16);
        System.out.println("Decimal version of " + toConvert + " is " + result);
    }

}

Pour aller plus loin

9 — Vérification des invariants

Coder et tester des boucles avec quelques cas, même judicieusement sélectionnés, ne suffit pas à garantir que votre algorithme renverra toujours le résultat attendu. En utilisant l’induction mathématique, vérifiez la correction des itérations que vous avez conçues durant cette activité.