Mathématiques en BCPST2

.

Python en BCPST2

TB Informatique 2023

Sujet TB 2023

from random import *

##1

def ber(p):
    if random() < p:
        return 1
    else:
        return 0

##2
T = [0, 1, 1, 0, 1, 0, 1, 1]

print(len(T))

##3

print(T[1])

##4

print([0,0,1,0,1,1,0,1])

##5

def tunnel(T):
    L=len(T)*[0]
    for i in range(0,len(T)-1):
        if T[i] == 1 and T[i+1]==0:
            L[i+1]=1
        if T[i] == 1 and T[i+1]==1:
            L[i]=1
    return L

print(tunnel(T))

##6
def tunnel2 (T,p):
    L=len(T)*[0]
    for i in range (0,len(T) -1):
        if T[i]==1 and T[i +1]==0:
            L[i+1]=1
        if T[i]==1 and T[i +1]==1:
            L[i]=1
    if T [0]==0:
        L[0]=ber(p)
    return (L)

##7
def evol2(T,n,p):
    L=T
    print(L)
    for i in range(n):
        L= tunnel2(L,p)
        print(L)

##8
T=[[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 1, 0, 0],
[0, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 1, 0, 0],
[0, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0]]

##9
def coq(T):
    L=len(T)*[0]
    for i in range(1,len(T)-1):
        s = T[i-1:i+2]
        if sum(s)%2==1:
            L[i]=1
    return(L)

##10
def evol4(T,n):
    A=[T]
    L=T
    for i in range(n):
        L= coq(L)
        A.append(L)
    return (A)

T = [0]*200+[1]+[0]*200
import matplotlib.pyplot as plt

plt.imshow(evol4(T,400))
plt.show()
##11
# prop3

##12

def voisins(M,i,j):
    V = []
    n=len(M)
    for u in range(max(0,i-1),min(n,i+2)):
        for v in range(max(0,j-1),min(n,j+2)):
            if u!=i and v!=j:
                V.append(M[u][v])
    return V

def epi(T,v):
    n = len(T)
    M = [[0 for _ in range(n)]for _ in range (n)]
    for i in range(n):
        for j in range(n):
            if T[i][j] == 0:
                k = sum(voisins(M,i,j))
                M[i][j]=ber(k*p)
            if T[i][j] == 1:
                M[i][j] = 1
    return M
TB Informatique 2024

Sujet TB 2024

    V##1,2,3,4
    L = [[200, 100, 155], [0, 254, 255]]

    print(L[1],L[1][1],len(L),len(L[1]))
    ##5
    def mz(n,m):
        return [m * [0] for k in range (n)]

    print(mz(2,3))

    ##6

    def taille(L):
        return len(L)*len(L[1])

    ##7

    def negatif(L):
        N = mz(len(L),len(L[0]))
        n = len(L)
        m = len(L[0])
        for i in range(n):
            for j in range(m):
                N[i][j] = 255 - L[i][j]
        return N

    ##8

    def monochrome(L,s):
        M=mz(len(L),len(L[0]))
        n = len(L)
        m = len(L[0])
        for i in range(n):
            for j in range(m):
                if L[i][j]  >= s:
                    M[i][j] = 255
        return M

    ##9

    def reflexion(L):
        R = mz(len(L),len(L[0]))
        n = len(L)
        m = len(L[0])
        for i in range(n):
            for j in range(m):
                R[i][j] = L[i][m - j-1]
        return R

    ##10

    def transpose(L):
        T=mz(len(L[0]),len(L))
        R = mz(len(L),len(L[0]))
        n = len(L)
        m = len(L[0])
        for i in range(n):
            for j in range(m):
                T[i][j] = L[j][i]
        return T

    ##11
    def indmin(L):
        k = 0
        n=len(L)
        for i in range(n):
            if L[i]<L[k]:
                k = i
        return k

    def selection(L):
        n= len(L)
        for i in range(n):
            k = i+indmin(L[i:])
            L[i],L[k] = L[k],L[i]
        return L

    ##12

    def indminPhoto(L):
        k = 0
        n=len(L)
        for i in range(n):
            if L[i][1]<L[k][1]:
                k = i
        return k

    def selectionPhoto(L):
        n= len(L)
        for i in range(n):
            k = i+indminPhoto(L[i:])
            L[i],L[k] = L[k],L[i]
        return L

    ##13
    def dicho(x,T):
        a=0
        b=len(T)-1
        while a < b:
            m=(a+b)//2
            if x==T[m]:
                return True
            elif x<T[m]:
                b=m
            else:
                a=m
        return False

    ##14
    def dichoPhoto(d,photos):
        a=0
        b=len(T)-1
        while a < b:
            m=(a+b)//2
            if x==T[m][1]:
                return True
            elif x<T[m][1]:
                b=m
            else:
                a=m
        return False

    ##15
    def nomPatients(images):
        noms=[]
        for key in images:
            n = images[key][2]
            if n not in noms:
                noms.append(n)
        return noms

    ##16
    def nombreDate(images,date):
        i = 0
        for key in images:
            if images[key][1]==date:
                i = i+1
        return i

    ##17
    def fracture(images):
        lab = []
        for key in images:
            l = images[key][3]
            f = (images[key][4]=='FRACTURE')
            if f and l not in lab:
                lab.append(l)
        return lab

    images ={
    109:[2.9 ,20221223 , "DUKIC","OCEANA","",""],
    203:[1.2 ,20221005 ,"MOING","RADIO1","FRACTURE", "TROUSSEAU"],
    405:[6.9 ,20230178 ,"KARL","RADIO2","ARTHROSE", "JENNER"],
    108:[4.1 ,20230206 ,"DUKIC","OCEANA","FRACTURE","PARE"],
    406:[2.0 ,20230612 ,"KARL", "RADIO2", "TENDINITE", "JENNER"]}
Tris

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 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()
Machine Ă  inventer des mots

Sujet

import random as rd

## Mot complétement aléatoire

def motAlea():
    s = ""
    lettre = ""
    while True:
        lettre = rd.choice(alphabet)
        if lettre == '>':
            return s
        if lettre != '<':
            s = s+lettre

## Traitement dico

dico = [line.rstrip("\n") for line in open("dico.txt")]
alphabet = ['<','>']
for mot in dico:
    for lettre in mot:
        if lettre not in alphabet:
            alphabet.append(lettre)

## Statistiques

def initProbaLettre1():
    d = {}
    for lettre1 in alphabet:
            d[lettre1] = 0
    return d

def initProba1():
    """
    Cree un dictionnaire dont les clefs sont les lettres de l'alphabet
    """
    d = {}
    for lettre in alphabet:
        d[lettre] = initProbaLettre1()
    return d

def proba1():
    """
    Met Ă  jour le dictionnaire des probas de suites de 2 lettres suite Ă  la lecture du mot, N Ă©tant le nombre de suites de deux lettres dans le dictionnaire
    """
    d = initProba1()
    N = 0
    for mot in dico:
        n = len(mot)
        d['<'][mot[0]] += 1
        N+=1
        for i in range(n-1):
            d[mot[i]][mot[i+1]] += 1
            N+=1
        d[mot[-1]]['>'] += 1
        N+=1
    for lettre1 in alphabet:
        for lettre2 in alphabet:
            d[lettre1][lettre2] /= N
    return d

## Générateur de mots

def genMot1(d):
    """
    Genere un mot en utilisant le dictionnaire de probabilites d
    """
    s = ""
    lettre = '<'
    lettre = rd.choices(list(d[lettre].keys()), weights = d[lettre].values())[0]
    # print(lettre)
    s += lettre
    while lettre != '>':
        lettre = rd.choices(list(d[lettre].keys()), weights = d[lettre].values())[0]
        s+= lettre
        if len(s) > 15:
            return genMot1(d)
    return s[:-1]

## Test
d1=proba1()
#
for _ in range(10):
    print(genMot1(d1))
#

## Mot le plus probable

d1=proba1()

def max_proba(d):
    m = 0
    l = ''
    for k in d:
        if d[k] > m:
            m = d[k]
            l = k
    return l

mot = ""
lettre = '<'
while lettre != '>':
    lettre = max_proba(d1[lettre])
    mot = mot + lettre
    if len(mot) > 20:
        break

print(mot[:-1])

## En comptant les suites de 3 lettres

def initProbaLettre2():
    print('foo')
    d = {}
    for lettre1 in alphabet:
            d[lettre1] = 0
    return d

def initProba2():
    d = {}
    for lettre1 in alphabet:
        d[lettre1] = {}
        for lettre2 in alphabet:
            d[lettre1][lettre2] = {}
            for lettre3 in alphabet:
                d[lettre1][lettre2][lettre3] = 0
    return d

def proba2():
    d = initProba2()
    N = 0
    for mot in dico:
        if len(mot)>1:
            n = len(mot)
            d['<'][mot[0]][mot[1]] += 1
            N+=1
            for i in range(n-2):
                d[mot[i]][mot[i+1]][mot[i+2]] += 1
                N+=1
            d[mot[-2]][mot[-1]]['>'] += 1
            N+=1
    for lettre1 in alphabet:
        for lettre2 in alphabet:
            for lettre3 in alphabet:
                d[lettre1][lettre2][lettre3] /= N
    return d

def genMot2(d,lmax=15):
    s = ""
    lettre1 = '<'
    lettre2 = rd.choice(alphabet)
    while lettre2 == '<' or lettre2=='>' or lettre2=='-':
        lettre2 = rd.choice(alphabet)
    s=s+lettre1+lettre2
    lettre = rd.choices(list(d[lettre1][lettre2].keys()), weights = d[lettre1][lettre2].values())[0]
    lettre1,lettre2 = lettre2,lettre
    s += lettre2
    while lettre2 != '>':
        if len(s)>lmax:
            return genMot2(d)
        lettre = rd.choices(list(d[lettre1][lettre2].keys()), weights = d[lettre1][lettre2].values())[0]
        lettre1,lettre2 = lettre2,lettre
        s+= lettre
    return s[1:-1]

## Test2

d2 = proba2()
print()
for _ in range(10):
    print(genMot2(d2))
MĂ©thode d'Euler

Archives

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