VaultBy ENSAMIENParrainage
Notebook

TDP 01 – Corrigés en Python

correction.ipynb

Ce notebook contient les solutions proposées aux exercices du TDP.

Partie 1 : Structures conditionnelles

1. Pair ou impair

n = 7
if n % 2 == 0:
    print(f"{n} est pair")
else:
    print(f"{n} est impair")
7 est impair

2. Maximum de trois nombres

a, b, c = 4, 9, 2

if a >= b and a >= c:
    maximum = a
elif b >= a and b >= c:
    maximum = b
else:
    maximum = c

print(f"Le maximum est {maximum}")
Le maximum est 9

3. Affichage de 3 chaînes séparées par *

s1, s2, s3 = "abc", "def", "ghi"

print(s1, s2, s3, sep="*")
abc*def*ghi

Partie 2 : Boucles

1. Racine carrée entière

import math

n = 49
racine = int(math.sqrt(n))

if racine * racine == n:
    print(f"La racine carrée entière de {n} est {racine}")
else:
    print(f"{n} n'a pas de racine carrée entière")
La racine carrée entière de 49 est 7

2. Produit scalaire de deux vecteurs

import random

n = 5

v = [random.randint(1, 10) for _ in range(n)]
w = [random.randint(1, 10) for _ in range(n)]

print("Vecteur v =", v)
print("Vecteur w =", w)

produit_scalaire = sum(v[i] * w[i] for i in range(n))
print("Produit scalaire =", produit_scalaire)
Vecteur v = [10, 4, 10, 6, 7]
Vecteur w = [4, 2, 3, 6, 3]
Produit scalaire = 135

3. Vérification d'un nombre premier

n = 97

if n < 2:
    print(f"{n} n'est pas un nombre premier")
else:
    premier = True
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            premier = False
            break
    if premier:
        print(f"{n} est un nombre premier")
    else:
        print(f"{n} n'est pas un nombre premier")
97 est un nombre premier

4. Inverser les chiffres d'un nombre

def inv(x):
    y = 0
    while x > 0:
        y = y * 10 + x % 10
        x //= 10
    return y

print(inv(1593))
3951

5. Expression bien parenthésée

def bien_parenthesee(expr):
    compteur = 0
    for c in expr:
        if c == '(':
            compteur += 1
        elif c == ')':
            compteur -= 1
            if compteur < 0:
                return False
    return compteur == 0

for e in ["(3 - (2 - 9))", "1 + 4", "((3)", "(4))", ")2+3(+5"]:
    print(e, "->", bien_parenthesee(e))
(3 - (2 - 9)) -> True
1 + 4 -> True
((3) -> False
(4)) -> False
)2+3(+5 -> False

    Type at least 2 letters. ↑ ↓ to move, Enter to open.