Algorithmique et Python en Terminale spé : cours complet
En Terminale spé, tu maîtrises Python : structures avancées, algorithmes mathématiques (dichotomie, suites, intégration numérique, simulations Monte-Carlo), et complexité.
Rappels Python
Variables, types, structures
x = 5
L = [1, 2, 3]
d = {"nom": "Léa", "age": 17}
if x > 0:
print("positif")
for i in range(10):
print(i)
while x < 100:
x += 1
Fonctions
def factorielle(n):
if n == 0:
return 1
return n * factorielle(n - 1)
Modules utiles
import math, random, statistics
import matplotlib.pyplot as plt
import numpy as np # optionnel
Algorithmes classiques
Dichotomie pour résoudre f(x)=0f(x) = 0
def dichotomie(f, a, b, eps):
while b - a > eps:
m = (a + b) / 2
if f(a) * f(m) < 0:
b = m
else:
a = m
return (a + b) / 2
Méthode des rectangles (intégration)
def integrale_rectangles(f, a, b, n):
h = (b - a) / n
return h * sum(f(a + i * h) for i in range(n))
Méthode des trapèzes
def integrale_trapezes(f, a, b, n):
h = (b - a) / n
s = (f(a) + f(b)) / 2
s += sum(f(a + i * h) for i in range(1, n))
return h * s
Suite de Fibonacci
def fibo(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
Calcul d'un terme d'une suite récurrente
def suite(u0, f, n):
u = u0
for _ in range(n):
u = f(u)
return u
print(suite(1, lambda x: 0.5 * x + 1, 100))
Simulations Monte-Carlo
Estimation de ππ
import random
def estim_pi(n):
cpt = 0
for _ in range(n):
x, y = random.random(), random.random()
if x*x + y*y <= 1:
cpt += 1
return 4 * cpt / n
print(estim_pi(100000)) # ≈ 3.14
Loi binomiale (simulation)
def simul_binomiale(n, p):
return sum(1 for _ in range(n) if random.random() < p)
# moyenne sur 10000 simulations
moyenne = sum(simul_binomiale(20, 0.3) for _ in range(10000)) / 10000
# ≈ 6
Marche aléatoire
def marche(n):
x = 0
pos = [0]
for _ in range(n):
x += random.choice([-1, 1])
pos.append(x)
return pos
plt.plot(marche(1000))
plt.show()
Recherche dans une liste
Linéaire
def cherche(L, x):
for i, v in enumerate(L):
if v == x:
return i
return -1
Dichotomique (liste triée)
def cherche_dicho(L, x):
a, b = 0, len(L) - 1
while a <= b:
m = (a + b) // 2
if L[m] == x: return m
elif L[m] < x: a = m + 1
else: b = m - 1
return -1
Tris
Tri par insertion
def tri_insertion(L):
for i in range(1, len(L)):
x, j = L[i], i - 1
while j >= 0 and L[j] > x:
L[j+1] = L[j]
j -= 1
L[j+1] = x
Tri par sélection
def tri_selection(L):
for i in range(len(L)):
m = i
for j in range(i+1, len(L)):
if L[j] < L[m]:
m = j
L[i], L[m] = L[m], L[i]
Complexité (introduction)
| Algo |
Complexité |
| Recherche linéaire |
O(n)O(n) |
| Recherche dichotomique |
O(logn)O(log n) |
| Tri insertion / sélection |
O(n2)O(n²) |
| Tri rapide / fusion |
O(nlogn)O(n log n) |
Récursivité
def somme(L):
if L == []:
return 0
return L[0] + somme(L[1:])
Attention à la pile de récursion : limite de profondeur en Python (∼1000~ 1000).
Erreurs fréquentes à éviter
- Mauvais index (commence à 00).
- Boucle infinie : vérifier la condition de sortie.
- Récursion sans cas de base : erreur.
- Modification d'une liste pendant qu'on la parcourt : bug.
- Trop de récursion : préférer l'itération si profondeur grande.
FAQ — Algorithmique et Python en Terminale spé
Pourquoi Python est-il utilisé en lycée ?
C'est un vrai langage, simple à apprendre, et utilisé dans la recherche et l'industrie (IA, data science, web).
Pourquoi étudier la complexité ?
Pour comparer des algorithmes : un algorithme en O(n)O(n) est bien meilleur qu'en O(n2)O(n²) pour nn grand.
À quoi servent les simulations Monte-Carlo ?
À estimer des probabilités difficiles à calculer théoriquement, à explorer des phénomènes complexes.
Récursivité ou itération ?
L'itération est généralement plus efficace en Python. La récursivité est plus claire pour certains problèmes (fractales, parcours d'arbres).