Mathématiques en BCPST2

.

Python en BCPST2

Oral G2E 2024

(Sujet)


## 1 Somme

def est_valide(ch):
    if ch[0] == '+' or ch[-1]=='+':
        return False
    n = len(ch)
    for i in range(n):
        if ch[i]=='+':
            if ch[i+1]=='+':
                return False
        else:
            if not ch[i].isdigit():
                return False
    return True

## 2 Evaluation

def evalue(ch):
    l = ch.split('+')
    s = 0
    for x in l:
        s = s+int(x)
    return s

## 3 Liste d'additions

def plus_grande_somme(l):
    ll = [evalue(x) for x in l]
    return max(ll)

## 4 Expressions arithmétiques

def calcule(a,b,op):
    if op == '+':
        return a+b
    if op == '-':
        return a-b
    if op == '*':
        return a*b
    if op == '/':
        return a//b

## 5 Evaluation

def evaluation(l):
    if len(l)==1: return l[0]
    else:
        a,op,b = l.pop(0), l.pop(0), l.pop(0)
        l = [calcule(a,b,op)] + l
        return evaluation(l)

def evaluation2(l):
    r=l[0]
    n = len(l)
    i=1
    while i<n:
        r = calcule(r,l[i+1],l[i])
        i=i+2
    return r

## 6 Expression postfixee

def postfix(l):
    ope = ['+','-','*','/']
    pile = []
    for x in l:
        if x in ope:
            b,a = pile.pop(),pile.pop()
            pile.append(calcule(a,b,x))
        else:
            pile.append(x)
    return pile[0]

## 7 Verification d'erreur

def postfix(l):
    ope = ['+','-','*','/']
    pile = []
    for x in l:
        if x in ope:
            if len(pile) <2: return 'ERR'
            b,a = pile.pop(),pile.pop()
            if x=='/' and b==0: return 'ERR'
            pile.append(calcule(a,b,x))
        else:
            pile.append(x)
    if len(pile)!=1: return 'ERR'
    return pile[0]
Algorithmes de tri

(Sujet)

## Tri par Insertion

def triInsertion(l):
    ll = l[:]
    n = len(ll)
    for i in range(n):
        element = ll[i]
        j = i
        while (j>0 and ll[j-1] > element):
            ll[j] = ll[j-1]
            j = j-1
        ll[j] = element
    return ll

def triInsertionMieux(l):
    ll = l[:]
    n = len(ll)
    for i in range(n):
        element = ll[i]
        j = i
        while (j>0 and ll[j-1] > element):
            j = j-1
        ll.insert(j,element)
        del(ll[i+1])
    return ll

## Tri fusion

def divise(l):
    n=len(l)
    return l[:n//2],l[n//2:]

def fusion(l1,l2):
    if l1 == []: return l2
    if l2 == []: return l1
    if l1[0] <= l2[0]:
        return [l1[0]] + fusion(l1[1:],l2)
    else:
        return [l2[0]] + fusion(l1,l2[1:])

def fusion(l1,l2):
    l = []
    while (l1!=[] and l2!=[]):
        if l1[0] > l2[0]:
            l.append(l2[0])
            del(l2[0])
        else:
            l.append(l1[0])
            del(l1[0])
    if l1==[]:
        return l + l2
    else:
        return l+l1

def triFusion(l):
    n = len(l)
    if n<=1:
        return l
    else:
        lg,ld = divise(l)
        lg,ld = triFusion(lg),triFusion(ld)
        return fusion(lg,ld)

## Quicksort

def partition(l):
    lg = []
    ld = []
    pivot = l[0]
    for elem in l[1:]:
        if elem < pivot:
            lg.append(elem)
        else:
            ld.append(elem)
    return lg,ld,pivot

def quicksort(l):
    n = len(l)
    if n <= 1:
        return l
    else:
        lg,ld,pivot = partition(l)
        lg = quicksort(lg)
        ld = quicksort(ld)
        return lg+[pivot]+ld

## Quicksort + insertion

def sedgesort(l):
    n = len(l)
    if n<=15:
        return triInsertionMieux(l)
    else:
        lg,ld,pivot = partition(l)
        lg = sedgesort(lg)
        ld = sedgesort(ld)
        return(lg+[pivot]+ld)

## Mediane

def nth_least(l,n):
    lg,ld,pivot = partition(l)
    kg = len(lg)
    if n==kg:
        return pivot
    elif n<kg:
        return nth_least(lg,n)
    else:
        return nth_least(ld,n-(kg+1))

def mediane(l):
    n = len(l)
    return nth_least(l,n//2)

## Test
import random as rd
import time
l = [rd.randint(-499,499) for _ in range(20000)]

t = time.time()
l_insert = triInsertion(l)
print("Tri par insertion :",time.time() - t)
t = time.time()
l_insertmieux = triInsertionMieux(l)
print("Tri par insertion mieux :",time.time() - t)
t = time.time()
l_fusion = triFusion(l)
print("Tri fusion :",time.time() - t)
t = time.time()
l_qs = quicksort(l)
print("Tri rapide :",time.time() - t)
t = time.time()
l_sedge = sedgesort(l)
print("Tri Sedge :",time.time() - t)
t = time.time()
l_sort = sorted(l)
print("Tri Python :",time.time() - t)
t = time.time()
Algorithme de Dijkstra

(Sujet)

## Exercice 1
import numpy as np

Exm1 = {
    0:[],
    1:[(2,0),(4,1),(5,3)],
    2:[(0,6),(1,2)],
    3:[],
    4:[(2,1)],
    5:[(3,2)]
    }

mat = np.array([[-1., -1., -1., -1., -1., -1.],
       [-1., -1.,  0., -1.,  1.,  3.],
       [ 6.,  2., -1., -1., -1., -1.],
       [-1., -1., -1., -1., -1., -1.],
       [-1., -1.,  1., -1., -1., -1.],
       [-1., -1., -1.,  2., -1., -1.]])

## Exercice 2

import numpy as np

def matriceVersListe(mat):
    n,_ = mat.shape
    d = dict()
    for i in range(n):
        l = []
        for j in range(n):
            if mat[i,j] != -1:
                l.append((j,mat[i,j]))
        d[i] = l
    return d

def listeVersMatrice(d):
    n = len(d)
    mat = -1*np.ones([n,n])
    for s in d:
        for (v,p) in d[s]:
            mat[s,v] = p
    return mat

## Exercice 3

def voisins(d,s):
    v = []
    for u,p in d[s]:
        v.append(u)
    return v

## Exercice 4

def cheminValide(d,chemin):
    n = len(chemin)
    for i in range(n-1):
        if chemin[i+1] not in voisins(d,chemin[i]):
            return False
    return True

## Exercice 5

def parcoursLargeur(d,s):
    visite = []
    file = [s]
    while file != []:
        print(file)
        sommet = file.pop(0)
        visite.append(sommet)
        for v in voisins(d,sommet):
            if v not in file and v not in visite:
                file.append(v)
    return visite

def parcoursProfondeur(d,s):
    visite = []
    pile = [s]
    while pile != []:
        print(pile)
        sommet = pile.pop()
        visite.append(sommet)
        for v in voisins(d,sommet):
            if v not in pile and v not in visite:
                pile.append(v)
    return visite

## Exercice 7

Exm = {
    0:[(1,7),(2,1)],
    1:[(3,4),(5,1)],
    2:[(1,5),(4,2),(5,7)],
    3:[],
    4:[(1,2),(3,5)],
    5:[(4,3)]
    }

def index_min_non_visite(l,v):
    """
    Donne l'index de l'element min dans une liste
    """
    k = -1
    min = float('inf')
    for i in range(len(l)):
        if l[i] < min and i not in v:
            k = i
            min = l[i]
    return k

def Dijkstra(g):
    s = 0
    d = [float('inf') for sommet in g]
    d[s]=0
    visites = [s]
    for (v,p) in g[s]:
        d[v] = p
    n = len(g)
    while len(visites) < n:
        u = index_min_non_visite(d,visites)
        visites.append(u)
        for (v,p) in g[u]:
            if v not in visites:
                d[v] = min(d[v],d[u]+p)
    return d

## Exercice 9

def Dijkstra(g):
    s = 0
    d = [float('inf') for sommet in g]
    o = [-1 for _ in g]
    d[s]=0
    visites = [s]
    for (v,p) in g[s]:
        d[v] = p
        o[v] =
    n = len(g)
    while len(visites) < n:
        u = index_min_non_visite(d,visites)
        visites.append(u)
        for (v,p) in g[u]:
            if v not in visites:
                if d[v] > d[u]+p:
                    d[v]= d[u]+p
                    o[v] = u
    return d,o

## Exercice 10

def distance(graphe,j):
    d, o = Dijkstra(graphe)
    k = j
    l = []
    while k!= 0:
        l.append(k)
        k = o[k]
    l.append(0)
    l.reverse()
    return l,d[j]
Méthode d'Euler

(Sujet)

import numpy as np
import matplotlib.pyplot as plt

## Euler

def Euler(F,t0,tf,y0,n):
    t=t0
    y=y0
    h=(tf-t0)/n
    abcisses=[t0]
    ordonnees=[y0]
    for i in range(n):
        y += h*F(t,y)
        t += h
        abcisses.append(t)
        ordonnees.append(y)
    return abcisses,ordonnees

a,o = Euler(lambda t,y: np.cos(t)-y,0,100,1,1000)
plt.plot(a,o)
plt.show()

## Euler systeme

def Euler_systeme(F,G,t0,tf,x0,y0,n):
    t=t0
    x=x0
    y=y0
    h=(tf-t0)/n
    temps=[t0]
    Lx=[x0]
    Ly=[y0]
    for i in range(n):
        x,y = x+h*F(t,x,y), y + h*G(t,x,y)
        t += h
        temps.append(t)
        Lx.append(x)
        Ly.append(y)
    return temps, Lx, Ly

# x et y en fonction du temps
t,x,y = Euler_systeme(lambda t,x,y:x*(3-2*y),lambda t,x,y: y*(-4+x),0,10,10,1,500000)
plt.plot(t,x); plt.plot(t,y)
plt.show()

## Euler EDO2

def Euler2(F,t0,tf,y0,dy0,n):
    f = lambda t,x,y: F(t,y,x)
    g = lambda t,x,y: x
    t,x,y = Euler_systeme(f,g,t0,tf,y0,dy0,n)
    return [t,y]

t,y = Euler2(lambda t,y,dy: -y,0,50,1,0,1000)
_,y2 = Euler2(lambda t,y,dy: -np.sin(y),0,50,1,0,1000)
plt.plot(t,y)
plt.plot(t,y2)
plt.show()

## RK4

def RK4(F,t0,tf,y0,n):
    t=t0
    y=y0
    h=(tf-t0)/n
    abcisses=[t0]
    ordonnees=[y0]
    for i in range(n):
        K1 = h*F(t,y)
        K2 = h * F(t+h/2,K1/2+y)
        K3 = h * F(t+h/2,K2/2+y)
        K4 = h * F(t+h,K3+y)
        y += (1/6)*(K1+2*K2+2*K3+K4)
        t += h
        abcisses.append(t)
        ordonnees.append(y)
    return abcisses,ordonnees

a,o = RK4(lambda t,y: np.cos(t)-y,0,100,1,1000)
plt.plot(a,o)
plt.show()

## odeint

from scipy.integrate import odeint

t = np.linspace(0,100,1000)
plt.plot(t,odeint(lambda y,t: np.cos(t)-y,1,t)); plt.show()
plt.plot(t,odeint(lambda y,t: np.array([-np.sin(y[1]),y[0]]),np.array([1,0]),t)[:,1]); plt.show()

## Lorenz
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

def FLorenz(v,t,sigma=10,beta=2.66,rho=30):
    xp = sigma*(v[1]-v[0])
    yp = rho*v[0] - v[1] - v[0]*v[2]
    zp = v[0]*v[1] - beta*v[2]
    return [xp,yp,zp]

t = np.linspace(0,50,10000)
v = odeint(FLorenz, [20,0,0],t)
ax.plot(v[:,0],v[:,1],v[:,2],linewidth=.9)
v = odeint(FLorenz, [10,0,0],t)
ax.plot(v[:,0],v[:,1],v[:,2],linewidth=.9)
v = odeint(FLorenz, [0.1,0,0],t)
ax.plot(v[:,0],v[:,1],v[:,2],linewidth=.9)
plt.show()
Bases de données

Archives

Ces documents ne concernent pas mes étudiants actuels, mais peuvent continuer d'intéresser certaines personnes.