Introduction to Algorithms & Python
What is an algorithm ?
Before the code, the method : a finite, ordered sequence of operations leading to a result.
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.
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.
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.
Designing an algorithm
- Inputs : identify the data needed.
- Processing : determine the steps/instructions to develop.
- Outputs : the results (screen, file, printer).
Seen as 4 more detailed steps : analysis → design → implementation (translation into a specific language) → testing.
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.
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).
Structure of an algorithm in pseudocode
- Header : the word
Algorithmfollowed by a name. - Declaration section : list of variables and constants used.
- Body : the instructions, between
BeginandEndbehavior.
Introduction to the Python language
Created in 1991 by Guido van Rossum, Python favors readability and simplicity.
Python
Python is a widely used, interpreted, object-oriented and high-level programming language with dynamic semantics, used for general-purpose programming.
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.
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.
Python 2 vs Python 3
| Python 2 | Python 3 |
|---|---|
print "Hello" | print("Hello") |
print "Hello", var | print("Hello", var) |
6/4 == 1 | 6/4 == 1.5 |
Python 2 and 3 are incompatible on several points : Python 3 is considered the reference version today.
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.
Basic instructions
Variables and constants
The basic building block of every program : named memory locations.
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.
Naming an identifier
- Always starts with a letter or an underscore (never a digit);
- Can then contain letters, digits, and
_; - No spaces or punctuation;
totoandTotoare different (case-sensitive);- Don't use a reserved keyword of the language.
Declaring a variable / a constant
A constant receives its value at declaration and no longer changes during execution :
Tracing variables
Give the values of A, B, C after execution :
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.
Basic data types
Each value has a type, which determines its size in memory and which operations are allowed.
Type
An type translates values from their binary representation into a representation suited to manipulation in a high-level language.
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.
bool — truth table
Stores TRUE/FALSE (True/False, 8 bits). Operations : NOT, AND, ORbehavior.
| A | B | A AND B | A OR B | A XOR B |
|---|---|---|---|---|
| T | T | T | T | F |
| T | F | F | T | T |
| F | T | F | T | T |
| F | F | F | F | F |
Simplifying a logical negation
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).
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) :
Useful functions : len(), type(), int()/float()/str(), sum(), max()/min(), abs(), round(), sorted(), ord()/chr(). Methods (dot notation) : string.upper(), etc.
| Operator | Meaning | Example |
|---|---|---|
+ | Concatenation | "abc"+"def" → 'abcdef' |
* | Repetition | "Fi!"*3 → 'Fi!Fi!Fi!' |
in | Contains? | "ed" in "med" → True |
[n] | nth character (index 0) | "abc"[0] → 'a' |
String formatting
The % marker precedes a formatting code : %d (integer), %f (real), %s (string), %.2f (2 decimals)...
Assignment and notation
Giving a value to a variable — it's not the same thing as a mathematical equality.
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.
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.
Variants of assignment in Python
Operations and type casting
Arithmetic, logic, comparison — and how to convert one type into another.
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.
Arithmetic, logical, and comparison operators
| Operation | Pseudocode | Python |
|---|---|---|
| Integer division | Div | // |
| Modulo (remainder) | Mod | % |
| Power | ^ | ** |
| Logical AND | AND | and |
| Logical OR | OR | or |
| Negation | NOT | not |
| Equality | = | == |
| Not equal | != | != |
| Membership test | — | in |
Other operators common to both notations : + - * /, < <= > >=, and augmented assignments += -= *= /=behavior.
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.
Type casting
The functions int(arg), float(arg), str(arg) convert (as far as possible) their argument to the corresponding type.
Input/output
Communicating with the user : reading input, displaying a result.
Reading input
In pseudocode : Read(List of variables). In Python, input() always reads input as text (a string) which must then be cast :
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).
Escape sequences
| Sequence | Meaning |
|---|---|
\\ | Prints a backslash |
\' / \" | Apostrophe / quote |
\n | Line break |
\t | Horizontal tab |
\xhh | Character as hexadecimal code |
Control structures: conditionals and loops
Sequential and conditional structures
The order of instructions is essential : sequential, then conditional based on a boolean expression.
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.
Conditional structure
Allows certain instructions to run only if a condition (a boolean-valued expression) is met. Simple and multi-choice structures are distinguished.
If ... Then ... Else
The Else clause is optional (simple form If...EndIf). A nested test generalizes this principle to more than two outcomes.
State of water (nested test)
Prefer nested tests over independent tests when the conditions concern the same variable and are mutually exclusive :
Select ... Do (multiple choice)
The selector is a variable/expression; each case is exclusive; the Else (optional) covers unforeseen values.
if / elif / else
match ... case (Python ≥ 3.10)
The Python equivalent of Select...Do, useful for comparing a variable against specific values :
Loops
Repeating a process : a known number of repetitions (For/for) or an unknown one (While/while).
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).
While ... Do
The condition is tested before before each iteration : if it is false from the start, the body is never executed.
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.
Repeat ... Until
Unlike While, the body is executed at least once (the condition is tested afterward, and the loop continues as long as it is false).
For ... Do
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.
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.
while
for and range()
range(start, stop, step) : a sequence from start (included) to stop (excluded), with start and start and step optional (default 0 and 1).
for/range() (end of section 3.7). Sections 3.8 (break/continue), 3.9 (indentation/blocks), 3.10 (comments), as well as Chapter 4 (
Tutorials & Labs
Each exercise comes with an expandable correction — try it first, check afterward. TD3 does not appear here : no problem statement
Basic instructions
Variables, operators, order of operations.
Variable values after execution
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.
Valid identifiers?
Var-65, AVERAGE A, 3rd_index, For, Var.1, If_A, N*, Else, 1, café, Number,n, result%final, @value, index, #text
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).
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) ?
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.
What does this algorithm do?
& is the concatenation operator for strings : C receives the string "423" followed by "12", i.e. C = "42312" (this is not a numeric addition).
Swapping two variables A and B
Write an algorithm that swaps the values of two variables A and B.
We use an auxiliary variable c so as not to lose the value of a during the assignment a ← bbehavior.
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)
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.
Why is this algorithm incorrect?
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*band not5bbehavior.
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
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.
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)
x = 2stays 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).
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
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).
Conditional structures
Solving simple problems with If/Else.
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.
Even or odd
Determine whether a given integer is even or odd.
Age category of a child
Chick (6-7), Pupil (8-9), Minor (10-11), Cadet (12+).
Photocopy bill (tiered pricing)
$0.10 for the first 10, $0.09 for the next 20, $0.08 beyond that.
Verified : for 45 copies, the bill is $4.0.
Tax based on age and sex
Men over 20 are taxable; women aged 18 to 35 are taxable; everyone else is not.
Name of the day of the week
Number between 1 and 7 → day name (1 = Sunday).
4-operation calculator
Simulate a calculator (+, -, *, /).
Even / odd-multiple-of-3 / neither
A number is a multiple of 3 if the remainder of its division by 3 is 0.
Solve ax + b = 0
Solve ax² + bx + c = 0
Arrays
Working with arrays and solving simple problems using loops.
Counting occurrences of 'a'
Read 10 characters into an array, count the number of occurrences of the letter 'a'.
We iterate through the array and increment a counter each time an 'a' is found — the basic loop-counting pattern.
Reversing an 8-element array
Put the last element first, and so on.
We swap the symmetric elements around the center (index i with n-1-i), without an auxiliary array.
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).
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.
Equality of two arrays
Test whether two integer arrays (size 10) are equal position by position.
break stops the loop as soon as a difference is found — no need to keep comparing.
Number of grade averages ≥ 10
Read n real grade averages (n≤100), display the number of averages ≥ 10.
2D array : class grades
5 students, 4 subjects. Each student's average, and the class average per subject.
A student's average → we iterate over a row; the class average for a subject → we iterate over a columnbehavior.
Triangles made of '+'
Two triangles of height n=3 (right-angled, then increasing by 2).
In triangle 2, row i contains 2i-1 symbols (1, 3, 5...).
2D arrays, sorting, and searching
Working with matrices, mastering sorting and searching algorithms.
Sum of two matrices
C[i][j] = A[i][j] + B[i][j]
Insertion sort (pseudocode)
Sort in increasing order an array T of n random reals.
Idea : we build the sorted part progressively by inserting each new element in its place, shifting larger elements
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.
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 :
4. Execution on T = [2, -1, 0, -4, 5, 3] (state at the end of each pass) :
| Pass | State of the array |
|---|---|
| Initial | 2, -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.
Selection sort (ages)
Sort an array of integers representing ages, in ascending order.
On each pass, we find the smallest remaining element and swap it with the current position.
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]
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.
First Python programs
Variables, types, operations, input/output.
Average of three numbers
Ask for three numbers, display their average.
Integer part and decimal part
For 45.478, display "Integer part 45 and decimal part 0.478".
Area of a circle
Read the radius, compute and display the area.
Volume of a right cone
V = 1/3 × π × r² × h
Iterative statements in Python
Writing, testing, and debugging programs with loops.
Factorial (while, then for)
Factorial of 5 = 1×2×3×4×5 = 120.
Average of grades entered from the keyboard
Dialogue : "How many grades", then each grade.
Verified with 12, 15.25, 13.5, 8.5 : average = 12.31.
Perfect number
An integer is perfect if it equals the sum of its divisors (e.g. : 6 = 1+2+3).
Verified for 6, 28, and 496 — all detected as perfect.
Multiples of a number (for loop)
x=3, limit=20 → 3, 6, 9, 12, 15, 18.
First odd numbers (while loop)
Display the first n odd numbers, starting from 1.
Arrays and loops (Python)
Translating the array problems from TD4 into Python.
Counting occurrences of 'a'
Identical to TD4 Ex1, coded directly in Python.
Searching for a value in an array
10 integers + a value V ; say whether V is present.
Reversing an 8-element array
Identical to TD4 Ex2, in Python.
Slicing [::-1] directly reverses the list (see Ch.2, substring extraction — the same principle applies to lists).
Arrays (continued)
Equality, splitting into even/odd, matrices — in Python.
Equality of two arrays
Identical to TD4 Ex4, in Python.
In Python, == on two lists already compares element by element — no manual loop needed.
Even and odd numbers
Identical to TD4 Ex3, in Python.
Sum of two matrices
Identical to TD5 Ex1, in Python.
Sorting and binary search
Translating the sorting algorithms given in pseudocode into Python.
Selection sort, step by step
Sort T by selection (ascending order), displaying each iteration.
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.
Insertion sort, step by step
Sort T by insertion (ascending order), displaying each iteration.
Binary search
Search for a value V in a sorted array T.
Faithful translation of the given algorithm : we shrink the interval [low, high] by half each iteration depending on whether V is smaller
What to absolutely remember
int()/float()behavior.