Revision sheet

Algorithms 1
Python.

Level : S1

From the first steps in algorithms to control structures in Python : variables, types, operations, conditions, and loops

Each TD/TP exercise comes with an expandable correction, so you can practice before checking.

Filter cards
All
Definition
Syntax / Formula
Example
Remark
Exercise
Key takeaways
Chapter 1

Introduction to Algorithms & Python

Section 1.1

What is an algorithm ?

Before the code, the method : a finite, ordered sequence of operations leading to a result.

Definition

Algorithm

An algorithm is a finite, ordered sequence of elementary operations, governed by control rules (sequencing, selection, iteration),

Concretely : a sequence of computation steps that takes a set of values as input and produces a set of values as output, independent of any programming language.

Remark

A word from Al-Khwarizmi

The term algorithm comes from the name of the mathematician Al-Khwārizmī (9thth century, Baghdad). Algorithms weren't born with computing : Euclid's algorithm for the GCD is over 2000 years old.

A given problem can have several different algorithms that solve it.

Definition

Key concepts

  • Program : a series of instructions that implements an algorithm.
  • Programming language : a conventional notation for expressing algorithms.
  • Compiler : translates the whole program into machine code before execution.
  • Interpreter : executes instructions directly, with no prior translation step.
Method

Designing an algorithm

  1. Inputs : identify the data needed.
  2. Processing : determine the steps/instructions to develop.
  3. Outputs : the results (screen, file, printer).

Seen as 4 more detailed steps : analysis → design → implementation (translation into a specific language) → testing.

Properties

A correct algorithm must...

  • Have a finite number of steps and operations per step;
  • Terminate after a finite number of operations and produce a result;
  • Be defined unambiguously, and be effective (achievable by a machine);
  • Have deterministicbehavior.
Remark

Representation : flowchart or pseudocode

Two possible notations : theflowchart (graphical, more visual but slower to produce) and pseudocode (text-based, faster to write and translate into a programming language — generally preferred).

Definition

Structure of an algorithm in pseudocode

  • Header : the word Algorithm followed by a name.
  • Declaration section : list of variables and constants used.
  • Body : the instructions, between Begin and Endbehavior.
Section 1.2

Introduction to the Python language

Created in 1991 by Guido van Rossum, Python favors readability and simplicity.

Definition

Python

Python is a widely used, interpreted, object-oriented and high-level programming language with dynamic semantics, used for general-purpose programming.

Remark

Interpreted, not compiled

A Python program is not translated into machine code before execution : there is no compilation step. This means a program can be tested faster, even though it runs slower than a compiled language.

Features

Why Python ?

  • Cross-platform (Windows, macOS, Linux, Android, iOS) and free;
  • High level, simple syntax, compact and readable programs (often 3 to 5 times shorter than in C/C++/Java);
  • Object-oriented, with multiple inheritance and operator overloading;
  • Extensive standard library; no explicit pointers; built-in exception system;
  • Extensible (can interface with C libraries); widely used in data analysis.
Example

Python 2 vs Python 3

Python 2Python 3
print "Hello"print("Hello")
print "Hello", varprint("Hello", var)
6/4 == 16/4 == 1.5

Python 2 and 3 are incompatible on several points : Python 3 is considered the reference version today.

Remark

Development environments

  • IDLE : the environment bundled with Python (console + editor + debugger).
  • Anaconda : a distribution for data science (includes NumPy, pandas, Jupyter).
  • Google Colab : Python notebooks 100 % online, on free cloud resources.
  • PyCharm : a full IDE for professional Python development.
Chapter 2

Basic instructions

Section 2.1 – 2.2

Variables and constants

The basic building block of every program : named memory locations.

Definition

Variable

A variable stores the value of a piece of data; its content can change during execution. In Python, a variable is an identifier

It is characterized by a name (identifier), a value, and a typebehavior.

Rules

Naming an identifier

  • Always starts with a letter or an underscore (never a digit);
  • Can then contain letters, digits, and _;
  • No spaces or punctuation;
  • toto and Toto are different (case-sensitive);
  • Don't use a reserved keyword of the language.
Declaration

Declaring a variable / a constant

In pseudocode: VAR rate : real In Python: rate = 0.0 # no separate type declaration

A constant receives its value at declaration and no longer changes during execution :

Constant PI ← 3.14 : real
Exercise

Tracing variables

Give the values of A, B, C after execution :

Variables A, B, C : Integer Begin A ← 7 ; B ← 17 ; A ← B ; B ← A+5 ; C ← A + B ; End
Correction

The right-hand side is evaluated before the assignment, using the previous value of the variable : A←7, B←17, then A←B so A=17 (B stays 17), then B←A+5 so B=22, then C←A+B=17+22=39. Final result : A=17, B=22, C=39.

Section 2.3

Basic data types

Each value has a type, which determines its size in memory and which operations are allowed.

Definition

Type

An type translates values from their binary representation into a representation suited to manipulation in a high-level language.

Numeric types

Integer, real, complex

  • Integer (int) : 4 bytes (32 bits); operations + - * div modbehavior.
  • Real (float) : 4 or 8 bytes; usual form "a.b" or scientific "a E b"; operations + - * /behavior.
  • Complex (complex) : imaginary part suffixed with jbehavior.
>>> (2+3j) + (4-7j) (6-4j) >>> (9+5j).real 9.0 >>> (9+5j).imag 5.0
Boolean type

bool — truth table

Stores TRUE/FALSE (True/False, 8 bits). Operations : NOT, AND, ORbehavior.

ABA AND BA OR BA XOR B
TTTTF
TFFTT
FTFTT
FFFFF
De Morgan's laws

Simplifying a logical negation

a ⟺ Not(Not(a)) Not(P AND Q) ⟺ (Not P) OR (Not Q) Not(P OR Q) ⟺ (Not P) AND (Not Q)
Definition

Character and string of characters

Character : 1 byte, corresponds to an ASCII code (e.g. : 'a', '3'). A character is actually an integer — the ASCII table provides the mapping.

String (str) : a sequence of characters, immutable once created (any transformation creates a new string).

Example

Working with a string : indexing, slicing, methods

Indexing starts at 0 (or -1 from the end); slices [i:j] extract a substring (the j bound excluded) :

>>> s = "Rayon X" >>> s[0] # 'R' >>> s[-1] # 'X' >>> s[1:4] # 'ayo' (from 1 included to 4 excluded) >>> s[:3] # 'Ray' (from the start to 3 excluded) >>> s[::-1] # 'X noyaR' (reversed string)

Useful functions : len(), type(), int()/float()/str(), sum(), max()/min(), abs(), round(), sorted(), ord()/chr(). Methods (dot notation) : string.upper(), etc.

OperatorMeaningExample
+Concatenation"abc"+"def" → 'abcdef'
*Repetition"Fi!"*3 → 'Fi!Fi!Fi!'
inContains?"ed" in "med" → True
[n]nth character (index 0)"abc"[0] → 'a'
Remark

String formatting

The % marker precedes a formatting code : %d (integer), %f (real), %s (string), %.2f (2 decimals)...

>>> '%.2f euros' % 2.394765 '2.39 euros'
Section 2.4

Assignment and notation

Giving a value to a variable — it's not the same thing as a mathematical equality.

Definition

Assignment

Assignment gives a value to a variable. In pseudocode : name ← value. In Python : name = valuebehavior.

The right-hand side is always evaluated before the assignment itself.

Careful

Assignment ≠ mathematical equality

a ← a+1 (increment) makes sense in programming but none in mathematics. Out loud, we say "a receives 2", not "a equals 2", to avoid confusion.

Assignment has an effect but no usable value inside an expression — hence the use of == (and not =) to compare in Python.

Formula

Variants of assignment in Python

v = 4 # simple assignment v += 2 # augmented assignment -> v = v+2 c = d = 8 # c and d both receive 8 e, f = 2.7, 5.1 # parallel assignment a, b = a+2, a*2 # everything is evaluated before assigning
Section 2.5 – 2.6

Operations and type casting

Arithmetic, logic, comparison — and how to convert one type into another.

Definition

Operator, operand, expression

  • Operator : a symbol that acts on variables (computation).
  • Operand : a variable, constant, or expression used by an operator.
  • Expression : a combination of operators and operands, evaluated during execution.
Formula

Arithmetic, logical, and comparison operators

OperationPseudocodePython
Integer divisionDiv//
Modulo (remainder)Mod%
Power^**
Logical ANDANDand
Logical ORORor
NegationNOTnot
Equality===
Not equal!=!=
Membership test—in

Other operators common to both notations : + - * /, < <= > >=, and augmented assignments += -= *= /=behavior.

Remark

Operator precedence (PEMDAS)

The precedence rules are the same as in mathematics : Parentheses, Exponents, Multiplication/Division, Addition/Subtraction. Comparison and boolean operators also have their own precedence order to respect in compound expressions.

Formula

Type casting

The functions int(arg), float(arg), str(arg) convert (as far as possible) their argument to the corresponding type.

Section 2.7

Input/output

Communicating with the user : reading input, displaying a result.

Syntax

Reading input

In pseudocode : Read(List of variables). In Python, input() always reads input as text (a string) which must then be cast :

>>> i = input("Enter an integer: ") >>> type(i) <class 'str'> >>> iplus = int(input("Enter an integer: ")) + 1
Syntax

Displaying results

In pseudocode : Write(List of expressions). In Python : print(List of expressions) — separates with a space and ends with a newline (both changeable via sep and end).

>>> a, b = 2, 5 >>> print(a, b) 2 5
Formula

Escape sequences

SequenceMeaning
\\Prints a backslash
\' / \"Apostrophe / quote
\nLine break
\tHorizontal tab
\xhhCharacter as hexadecimal code
Chapter 3

Control structures: conditionals and loops

Section 3.1 – 3.3

Sequential and conditional structures

The order of instructions is essential : sequential, then conditional based on a boolean expression.

Definition

Sequential instruction

A series of instructions executed one after another, in the order they appear, with no jump or reordering. This is the basis of every algorithm.

Begin Instruction 1 ; Instruction 2 ; ... End
Definition

Conditional structure

Allows certain instructions to run only if a condition (a boolean-valued expression) is met. Simple and multi-choice structures are distinguished.

Pseudocode syntax

If ... Then ... Else

If <Condition> then Instructions 1 ; Else Instructions 2 ; EndIf

The Else clause is optional (simple form If...EndIf). A nested test generalizes this principle to more than two outcomes.

Example

State of water (nested test)

Prefer nested tests over independent tests when the conditions concern the same variable and are mutually exclusive :

If (t <= 0) then Write("Solid state") ; Else If (t < 100) then Write("Liquid state") ; Else Write("Gaseous state") ; EndIf EndIf
Pseudocode syntax

Select ... Do (multiple choice)

Select <Selector> do Value 1 : Instruction 1 ; Value 2 : Instruction 2 ; Else Default instruction(s) ; EndSelect

The selector is a variable/expression; each case is exclusive; the Else (optional) covers unforeseen values.

Python syntax

if / elif / else

if condition1: instruction1 elif condition2: instruction2 else: instruction3
Python syntax

match ... case (Python ≥ 3.10)

The Python equivalent of Select...Do, useful for comparing a variable against specific values :

match month: case "december" | "january" | "february": print("Winter") case "march" | "april" | "may": print("
Section 3.6 – 3.7

Loops

Repeating a process : a known number of repetitions (For/for) or an unknown one (While/while).

Definition

Loop and counter

A loop (iteration) repeats a set of instructions. A distinction is made between a known number of repetitions (For loop) and an unknown one (While, Repeat...Until).

Pseudocode syntax

While ... Do

While <Condition> do Instruction(s) ; EndWhile

The condition is tested before before each iteration : if it is false from the start, the body is never executed.

Careful

The infinite loop trap

An instruction in the loop body must make the condition evolve from true to false, otherwise the program runs forever. This is the most common mistake with While/whilebehavior.

Pseudocode syntax

Repeat ... Until

Repeat Instruction(s) ; Until <Condition>

Unlike While, the body is executed at least once (the condition is tested afterward, and the loop continues as long as it is false).

Pseudocode syntax

For ... Do

For counter ← VI to VF [Step p] Do Instruction(s) EndFor

The counter is initialized to VI and incremented by 1 (or by the given step) up to VF. The For loop is a special case of While where the number of iterations is known in advance.

Remark

Which loop to choose ?

  • Number of iterations known known in advance → For;
  • Number unknown, condition tested before → While;
  • Number unknown, but at least one execution needed → Repeat...Untilbehavior.
Python syntax

while

c = 0 while c < 10: print(7*c) c = c + 1
Python syntax

for and range()

for e in [1, 4, 5, 0, 9, 1]: print(e) for i in range(5): # 0,1,2,3,4 print(i) for i in range(1, 11, 2): # 1,3,5,7,9 print(i) for i in range(10, 0, -1):# 10,9,...,1 print(i)

range(start, stop, step) : a sequence from start (included) to stop (excluded), with start and start and step optional (default 0 and 1).

Scope note : this summary faithfully covers the content provided, up to the for/range() (end of section 3.7). Sections 3.8 (break/continue), 3.9 (indentation/blocks), 3.10 (comments), as well as Chapter 4 (
Exercises

Tutorials & Labs

Each exercise comes with an expandable correction — try it first, check afterward. TD3 does not appear here : no problem statement

All
TD1
TD2
TD4
TD5
TP1
TP3
TP4
TP5
TP6
TD 1

Basic instructions

Variables, operators, order of operations.

TD1 · Ex 1
Exercise

Variable values after execution

Variables A, B, C : Integer Begin A ← -6 ; B ← 2 ; C ← A + B ; A ← 0 ; C ← B - A ; End
Correction

Step by step : A=-6, B=2, C=A+B=-4, then A=0 (overwrites -6), then C=B-A=2-0=2.

Final result : A = 0, B = 2, C = 2.

TD1 · Ex 2
Exercise

Valid identifiers?

Var-65, AVERAGE A, 3rd_index, For, Var.1, If_A, N*, Else, 1, café, Number,n, result%final, @value, index, #text

Correction

Accepted : If_A, index — start with a letter, contain only letters/digits/underscore.

Rejected : Var-65 (hyphen), AVERAGE A (space), 3rd_index (starts with a digit), For/Else (reserved keywords), Var.1 (dot), N* (symbol), 1 (digit alone), café (not a standard alphabetic letter), Number,n (comma), result%final/@value/#text (forbidden symbols).

TD1 · Ex 3
Exercise

Boolean result of the tests (a=6, b=-5, c=0.8)

(b>0) or (c>1) ? · not((b>a) and (c>b)) ? · ((b>a) and (c>b)) or (a<0) ? · (b>a) and (c>b) ? · (b>a) and (c<0) ? · not(c<a) ?

Correction

With a=6, b=-5, c=0.8 : (b>0) or (c>1) → False · not((b>a) and (c>b)) → True · ((b>a) and (c>b)) or (a<0) → False · (b>a) and (c>b) → False · (b>a) and (c<0) → False · not(c<a) → Falsebehavior.

TD1 · Ex 4
Exercise

What does this algorithm do?

Variables A, B, C : string Begin A ← "423" ; B ← "12" ; C ← A & B ; End
Correction

& is the concatenation operator for strings : C receives the string "423" followed by "12", i.e. C = "42312" (this is not a numeric addition).

TD1 · Ex 5
Exercise

Swapping two variables A and B

Write an algorithm that swaps the values of two variables A and B.

Correction
Variables a, b, c : Integer Begin write("Enter the values of a, b") ; read(a, b) ; c ← a ; a ← b ; b ← c ; End

We use an auxiliary variable c so as not to lose the value of a during the assignment a ← bbehavior.

TD1 · Ex 6
Exercise

Precedence and evaluating expressions

1. Precedence order of ((3*a) - x^2) - (((c-d)/(a/b))/d) ?

2. Evaluate : 5 + 2*6 - 4 + (8+2^3)/(2-4+5*2)

Correction

1. Order : parentheses → exponent → multiplication → division → addition → subtractionbehavior.

2. 5 + 12 - 4 + (8+8)/(2-4+10) = 5+12-4+16/8 = 17-4+2 = 15behavior.

TD1 · Ex 7
Exercise

Why is this algorithm incorrect?

Variables a, b : Integer c : Real Begin c ← a + 5 ; b ← c ; a*2 ← 7 + c ; b ← 5b + 7 ; End
Correction
  • b ← c : type mismatch — b is an Integer, c is a Real.
  • a*2 ← 7+c : the left-hand side of an assignment must be a simple variable, not an expression.
  • b ← 5b + 7 : invalid syntax — an explicit operator is required, 5*b and not 5bbehavior.
TD1 · Ex 8
Exercise

Values of a through k

a←7/2 · b←7 DIV 2 · c←7 MOD 2 · d←'t'<'w' · e←"Mary">"Paul" · f←(5!=2) · g←"mary">"Paul" · h←Not(5=2) · i←(4<6)AND(9>2) · j←(2<0)OR

Correction

a=3.5 · b=3 · c=1 · d=True · e=False (alphabetical order : "Mary" < "Paul") · f=True · g=True (lowercase > uppercase in ASCII code) · h=True · i=True · j=False · k=True.

TD1 · Ex 9
Exercise

Rewrite using only comparison and logic

x = 2 · x < 6 · x-2 > 7 · 0 < x < 3 · 3*x > 18 · a XOR b · Not(x>=0) · Not(Grade<0 OR Grade>20)

Correction
  • x = 2 stays as is (already a comparison).
  • 0 < x < 3 ⟺ (x>0) AND (x<3) (a double inequality to break down).
  • a XOR b ⟺ (a AND Not b) OR (Not a AND b)behavior.
  • Not(x>=0) ⟺ x < 0behavior.
  • Not(Grade<0 OR Grade>20) ⟺ (Grade>=0) AND (Grade<=20) (De Morgan's law).
TD1 · Ex 10
Exercise

Values of a, b, c, d according to precedence

a←4*2+5 · b←5+3*2-6 · c←a>b AND 7=2 OR a<b · d←a>b AND 7=2 OR a<b

Correction

a = 4*2+5 = 13. b = 5+3*2-6 = 5+6-6 = 5. Since a=13 > b=5 : (a>b) is True, (7=2) is False, (a<b) is False. With AND taking precedence over OR : (True AND False) OR False = False OR False = False for both c and d (identical formulas here).

TD 2

Conditional structures

Solving simple problems with If/Else.

TD2 · Ex 1
Exercise

Sign of a product without computing it

Ask for two numbers and report whether their product is negative, positive, or zero — without ever computing that product.

Correction
Variables a, b : Integer Begin write("Enter the values of a, b") ; read(a, b) ; If ((a>0 AND b>0) OR (a<0 AND b<0)) then
TD2 · Ex 2
Exercise

Even or odd

Determine whether a given integer is even or odd.

Correction
n = int(input("Enter the value of n: ")) if n % 2 == 0: print("n is even") else: print("n is odd")
TD2 · Ex 3
Exercise

Age category of a child

Chick (6-7), Pupil (8-9), Minor (10-11), Cadet (12+).

Correction
x = int(input("Enter the child's age: ")) if 6 <= x <= 7: print("Chick") elif 8 <= x <= 9: print("Pupil") elif 10
TD2 · Ex 4
Exercise

Photocopy bill (tiered pricing)

$0.10 for the first 10, $0.09 for the next 20, $0.08 beyond that.

Correction
n = int(input("Enter the number of photocopies: ")) if n <= 10: p = n * 0.10 elif n <= 30: p = 10*0.10 + (n-10)*0.09 else

Verified : for 45 copies, the bill is $4.0.

TD2 · Ex 5
Exercise

Tax based on age and sex

Men over 20 are taxable; women aged 18 to 35 are taxable; everyone else is not.

Correction
sex = input("Enter sex M/F: ") age = int(input("Enter age: ")) taxable = (sex == "M" and age > 20) or (sex == "F" and 18 <= a
TD2 · Ex 6
Exercise

Name of the day of the week

Number between 1 and 7 → day name (1 = Sunday).

Correction
j = int(input("Enter the day number: ")) match j: case 1: print("Sunday") case 2: print("Monday") case 3: print(
TD2 · Ex 7
Exercise

4-operation calculator

Simulate a calculator (+, -, *, /).

Correction
a = float(input("Enter the value of a: ")) b = float(input("Enter the value of b: ")) op = input("Enter the operation (+,-,*,/)
TD2 · Ex 8
Exercise

Even / odd-multiple-of-3 / neither

A number is a multiple of 3 if the remainder of its division by 3 is 0.

Correction
n = int(input("Enter a number: ")) if n % 2 == 0: print("This number is even") elif n % 3 == 0: print("This number is odd
TD2 · Ex 9
Exercise

Solve ax + b = 0

Correction
a = float(input("Enter a: ")) b = float(input("Enter b: ")) if a == 0: if b == 0: print("Infinitely many solutions")
TD2 · Ex 10
Exercise

Solve ax² + bx + c = 0

Correction
import math a = float(input("Enter a: ")) b = float(input("Enter b: ")) c = float(input("Enter c: ")) if a == 0: print("
TD 4

Arrays

Working with arrays and solving simple problems using loops.

TD4 · Ex 1
Exercise

Counting occurrences of 'a'

Read 10 characters into an array, count the number of occurrences of the letter 'a'.

Correction
array = [] for i in range(10): c = input("Character " + str(i) + ": ") array.append(c) counter = 0 for c in array:

We iterate through the array and increment a counter each time an 'a' is found — the basic loop-counting pattern.

TD4 · Ex 2
Exercise

Reversing an 8-element array

Put the last element first, and so on.

Correction
T = [15, 20, 13, 98, 75, 12, 23, 65] n = len(T) for i in range(n // 2): T[i], T[n-1-i] = T[n-1-i], T[i] print(T) # [65, 23, 1

We swap the symmetric elements around the center (index i with n-1-i), without an auxiliary array.

TD4 · Ex 3
Exercise

Array of even and odd numbers

a) Display only the odd values. b) Number of values given by the user. c) Split into two arrays (even / odd).

Correction
n = int(input("How many values? ")) T = [int(input("Value: ")) for _ in range(n)] even = [x for x in T if x % 2 == 0] odd = [x

A single pass is enough : for each element, we add it to the even or odd array based on x % 2. Question (a) amounts to the same thing, just only displaying oddbehavior.

TD4 · Ex 4
Exercise

Equality of two arrays

Test whether two integer arrays (size 10) are equal position by position.

Correction
T1 = [1,2,7,9,0,3,1,8,4,6] T2 = [1,2,7,5,0,3,1,8,4,6] equal = True for i in range(len(T1)): if T1[i] != T2[i]: equal =

break stops the loop as soon as a difference is found — no need to keep comparing.

TD4 · Ex 5
Exercise

Number of grade averages ≥ 10

Read n real grade averages (n≤100), display the number of averages ≥ 10.

Correction
n = int(input("Number of grade averages (<=100): ")) averages = [float(input("Average: ")) for _ in range(n)] counter = sum(1 for m
TD4 · Ex 6
Exercise

2D array : class grades

5 students, 4 subjects. Each student's average, and the class average per subject.

Correction
num_students, num_subjects = 5, 4 grades = [[float(input(f"Student {i+1}, subject {j+1}: ")) for j in range(num_subjects)] for i in ran

A student's average → we iterate over a row; the class average for a subject → we iterate over a columnbehavior.

TD4 · Ex 7
Exercise

Triangles made of '+'

Two triangles of height n=3 (right-angled, then increasing by 2).

Correction
n = 3 # Triangle 1: "+", "+ +", "+ + +" for i in range(1, n+1): print(" ".join(["+"] * i)) # Triangle 2: "+", "+ + +", "+ +

In triangle 2, row i contains 2i-1 symbols (1, 3, 5...).

TD 5

2D arrays, sorting, and searching

Working with matrices, mastering sorting and searching algorithms.

TD5 · Ex 1
Exercise

Sum of two matrices

C[i][j] = A[i][j] + B[i][j]

Correction
A = [[1,2],[3,4]] B = [[5,6],[7,8]] n, m = len(A), len(A[0]) C = [[A[i][j] + B[i][j] for j in range(m)] for i in range(n)] print(C
TD5 · Ex 2
Exercise

Insertion sort (pseudocode)

Sort in increasing order an array T of n random reals.

Correction
For i ← 1 to n-1 Do next_elt ← T[i] ; j ← i-1 ; While (j>=0 AND next_elt < T[j]) do T[j+1] ← T[j] ;

Idea : we build the sorted part progressively by inserting each new element in its place, shifting larger elements

TD5 · Ex 3
Exercise

Identifying a sorting algorithm from a diagram

The diagram traces the execution on T = [8, 2, 9, 4, 1] : at each pass, the largest remaining element moves toward the end (the shaded zone that grows), with the end-of-pass states [2,8,4,1,9] → [2,4,1,8,9] → [2,1,4,8,9] → [1,2,4,8,9]behavior.

1. Which sorting algorithm is used ? 2. Recall its principle. 3. Write the algorithm. 4. Run it (ascending sort) on T = [2, -1, 0, -4, 5, 3]behavior.

Correction

1. Algorithm : the bubble sort . It is recognized by the shaded zone growing from the end of the array with each pass — the signature of bubble sort, as distinguished from selection sort (which builds the sorted part from the start) and insertion sort (which shifts elements rather than comparing adjacent pairs).

2. Principle : we scan the array comparing each element to its right-hand neighbor; if they are out of order, we swap them. By the

3. Algorithm :

For i ← 0 to n-2 Do For j ← 0 to n-2-i Do If (T[j] > T[j+1]) then swap T[j] and T[j+1] ; End
def bubble_sort(T): n = len(T) for i in range(n-1): for j in range(n-1-i): if T[j] > T[j+1]:

4. Execution on T = [2, -1, 0, -4, 5, 3] (state at the end of each pass) :

PassState of the array
Initial2, -1, 0, -4, 5, 3
Pass 1-1, 0, -4, 2, 3, 5
Pass 2-1, -4, 0, 2, 3, 5
Pass 3-4, -1, 0, 2, 3, 5
Pass 4 and 5-4, -1, 0, 2, 3, 5 (unchanged — already sorted)

The array is fully sorted as of pass 3 ; subsequent passes make no further swaps.

TD5 · Ex 4
Exercise

Selection sort (ages)

Sort an array of integers representing ages, in ascending order.

Correction
ages = [34, 12, 45, 8, 23] n = len(ages) for i in range(n-1): posmin = i for j in range(i+1, n): if ages[j] < ages

On each pass, we find the smallest remaining element and swap it with the current position.

TD5 · Ex 5
Exercise

Binary search

1. Can binary search be applied to [-4,1,3,0,5,8] to look for 2 ? 2. How many iterations to find 15 in [1,2,15,17,30] 

Correction

1. No : the array [-4,1,3,0,5,8] is not sorted, a required condition for binary search.

2. In [1,2,15,17,30] (5 elements, indices 0-4) : mid=(0+4)//2=2 → T[2]=15 = the value being searched for, directly. 1 iteration is enough.

def binary_search(T, V): low, high = 0, len(T) - 1 while low <= high and V != T[(low+high)//2]: mid = (low+high)//2
TP 1

First Python programs

Variables, types, operations, input/output.

TP1 · Ex 1
Exercise

Average of three numbers

Ask for three numbers, display their average.

Correction
num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) num3 = float(input("Enter
TP1 · Ex 2
Exercise

Integer part and decimal part

For 45.478, display "Integer part 45 and decimal part 0.478".

Correction
a = float(input("Enter the first real number: ")) print("The integer part is:", int(a)) print("The decimal part is:", a - int(a
TP1 · Ex 3
Exercise

Area of a circle

Read the radius, compute and display the area.

Correction
import math radius = float(input("Enter the circle radius: ")) area = math.pi * (radius**2) print("The area of the circle is:", area)
TP1 · Ex 4
Exercise

Volume of a right cone

V = 1/3 × π × r² × h

Correction
import math r = float(input("Enter the cone radius: ")) h = float(input("Enter the cone height: ")) volume = (1/3) * math.p
TP 3

Iterative statements in Python

Writing, testing, and debugging programs with loops.

TP3 · Ex 1
Exercise

Factorial (while, then for)

Factorial of 5 = 1×2×3×4×5 = 120.

Correction
n = int(input("Enter a number: ")) # With while fact = 1 i = 1 while i <= n: fact *= i i += 1 print("Factorial (while
TP3 · Ex 2
Exercise

Average of grades entered from the keyboard

Dialogue : "How many grades", then each grade.

Correction
n = int(input("How many grades: ")) total = 0 for i in range(1, n+1): grade = float(input(f"Grade {i}: ")) total += grade

Verified with 12, 15.25, 13.5, 8.5 : average = 12.31.

TP3 · Ex 3
Exercise

Perfect number

An integer is perfect if it equals the sum of its divisors (e.g. : 6 = 1+2+3).

Correction
N = int(input("Enter an integer: ")) total = 0 for d in range(1, N): if N % d == 0: total += d if total == N: pri

Verified for 6, 28, and 496 — all detected as perfect.

TP3 · Ex 4
Exercise

Multiples of a number (for loop)

x=3, limit=20 → 3, 6, 9, 12, 15, 18.

Correction
x = int(input("Enter x: ")) limit = int(input("Enter the limit: ")) for i in range(x, limit+1, x): print(i, end=" ")
TP3 · Ex 5
Exercise

First odd numbers (while loop)

Display the first n odd numbers, starting from 1.

Correction
n = int(input("How many odd numbers to display? ")) counter = 0 number = 1 while counter < n: print(number, end=" ")
TP 4

Arrays and loops (Python)

Translating the array problems from TD4 into Python.

TP4 · Ex 1
Exercise

Counting occurrences of 'a'

Identical to TD4 Ex1, coded directly in Python.

Correction
array = [] for i in range(10): c = input("Character " + str(i+1) + ": ") array.append(c) print("Occurrences of 'a':"
TP4 · Ex 2
Exercise

Searching for a value in an array

10 integers + a value V ; say whether V is present.

Correction
T = [int(input(f"T[{i}] = ")) for i in range(10)] V = int(input("Value to search for: ")) if V in T: print("V is found in
TP4 · Ex 3
Exercise

Reversing an 8-element array

Identical to TD4 Ex2, in Python.

Correction
T = [15, 20, 13, 98, 75, 12, 23, 65] T_reversed = T[::-1] print(T_reversed) # [65, 23, 12, 75, 98, 13, 20, 15]

Slicing [::-1] directly reverses the list (see Ch.2, substring extraction — the same principle applies to lists).

TP 5

Arrays (continued)

Equality, splitting into even/odd, matrices — in Python.

TP5 · Ex 1
Exercise

Equality of two arrays

Identical to TD4 Ex4, in Python.

Correction
T1 = [1,2,7,9,0,3,1,8,4,6] T2 = [1,2,7,5,0,3,1,8,4,6] print("TRUE" if T1 == T2 else "FALSE") # FALSE

In Python, == on two lists already compares element by element — no manual loop needed.

TP5 · Ex 2
Exercise

Even and odd numbers

Identical to TD4 Ex3, in Python.

Correction
n = int(input("How many values? ")) T = [int(input("Value: ")) for _ in range(n)] even = [x for x in T if x % 2 == 0] odd = [x
TP5 · Ex 3
Exercise

Sum of two matrices

Identical to TD5 Ex1, in Python.

Correction
A = [[1,2],[3,4]] B = [[5,6],[7,8]] C = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))] print(C)
TP 6

Sorting and binary search

Translating the sorting algorithms given in pseudocode into Python.

TP6 · Ex 1
Exercise

Selection sort, step by step

Sort T by selection (ascending order), displaying each iteration.

Correction
n = int(input("Enter the size of array T: ")) T = [int(input(f"Enter the value of T[{i}] = ")) for i in range(n)] for i in

Direct translation of the given algorithm : on each pass i, we find the minimum of the remainder of the array and swap it with position ibehavior.

TP6 · Ex 2
Exercise

Insertion sort, step by step

Sort T by insertion (ascending order), displaying each iteration.

Correction
n = int(input("Enter the size of array T: ")) T = [int(input(f"Enter the value of T[{i}] = ")) for i in range(n)] for i in
TP6 · Ex 3
Exercise

Binary search

Search for a value V in a sorted array T.

Correction
n = int(input("Enter the size of array T: ")) T = [int(input(f"Enter the value of T[{i}] = ")) for i in range(n)] V = int(in

Faithful translation of the given algorithm : we shrink the interval [low, high] by half each iteration depending on whether V is smaller

Definition
Syntax / Formula
Example
Remark
Exercise
Correction
Key takeaways
★ Summary

What to absolutely remember

Algorithm : a finite, ordered, unambiguous sequence of operations leading to a result.
Variable : name + value + type; assignment always evaluates the right-hand side before assigning to the left.
Basic types : integer, real, boolean, complex, character, string — each with its own operations.
Conditionals : If/Else in pseudocode ↔ if/elif/else in Python; Select...Do ↔ match...case.
Loops : For/for when the number of iterations is known; While/while otherwise — always make the condition evolve.
input() always returns a string : remember to cast with int()/float()behavior.