Premier commit, tous les documents d'info faits jusque là

This commit is contained in:
Mysaa 2021-03-03 20:19:01 +01:00
commit 5ddf3c740c
19 changed files with 2059 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__

140
Barbare.ml Normal file
View File

@ -0,0 +1,140 @@
let rempliru u i =
u.(i) <- 15731*u.(i-1) mod 32003;;
let getu u0 = let arr = Array.make 40000 0 in
arr.(0) <- u0;
for i=1 to 39999 do
rempliru arr i
done;
arr;;
let uarr = getu 1;;
let u i = uarr.(i);;
let v i j = u (1+i+(j*(j-1)/2));;
u 1000;;
u 10000;;
u 30000;;
let g m n = let adj = Array.make n (Array.make n false) in
for i=0 to (n-1) do
adj.(i) <- Array.make n false;
for j=0 to (i-1) do
adj.(i).(j) <- ((v j i) mod m) = 0
done;
for j=i+1 to (n-1) do
adj.(i).(j) <- ((v i j) mod m) = 0
done
done;
adj;;
let aretes g = let n = Array.length g and count = ref 0 in
for i=0 to (n-1) do
for j=0 to (n-1) do
if g.(i).(j) then
count := !count+1
done
done;
!count/2;;
g 5 10;;
aretes(g 5 10);;
aretes(g 10 50);;
aretes(g 50 250);;
let deg g = let n = Array.length g in
let count = Array.make n 0 in
for i=0 to (n-1) do
for j=0 to (n-1) do
if g.(i).(j) then
count.(i) <- count.(i)+1
done
done;
count;;
let degre m n = deg (g m n);;
let max arr = let m = ref arr.(0) in
for i=1 to (Array.length arr)-1 do
if arr.(i) > !m
then m := arr.(i)
done;
!m;;
let minLastIndex arr = let im = ref 0 in
for i=1 to (Array.length arr)-1 do
if arr.(i) <= arr.(!im)
then im := i
done;
!im;;
let maxFirstIndex arr = let im = ref 0 in
for i=1 to (Array.length arr)-1 do
if arr.(i) > arr.(!im)
then im := i
done;
!im;;
max (degre 5 10);;
max (degre 10 50);;
max (degre 50 250);;
minLastIndex (degre 5 10);;
minLastIndex (degre 10 50);;
minLastIndex (degre 50 250);;
maxFirstIndex (degre 5 10);;
maxFirstIndex (degre 10 50);;
maxFirstIndex (degre 50 250);;
(*** 2 Méthode éxacte ***)
open List;;
let rec putall l x rst=
match l with
| [] -> rst
| e::s -> (x::e):(putall s x);;
let rec llen l = match l with
| [] -> 0
| e::s -> 1+(llen s);;
let rec parties k l = let n = llen l in
if k=0 then [ [] ]
else
if k=n then [ l ]
else
let l0::lr = l in
(putall (parties (k-1) lr) l0 [])@(parties k lr);;
let rec lin l x = match l with
| [] -> false
| e::s -> x=e || (lin s x);;
let tester l g = let n = Array.length g and out = ref true in
for i = 0 to n-1 do
for j = 0 to n-1 do
if g.(i).(j) then
out := !out && ((lin l i) || (lin l j))
done
done;
!out;;
exception PasDeCouverture;;
let rec testerliste ll g = match ll with
| [] -> raise PasDeCouverture
| l::s -> if tester l g
then l
else testerliste s g;;
let rec range i n = match n-i with
| 0 -> []
| _ -> i::(range (i+1) n);;
let rec testall g k = let n = Array.length g in
let l = range 0 (n-1) in
try (testerliste (parties k l) g)
with PasDeCouverture -> testall g (k+1);;
testall (g 5 10) 0;;
testall (g 6 16) 0;;
testall (g 7 20) 0;;
range 0 4;;
parties 1 (range 0 4);;
parties 2 (range 0 4);;
parties 3 (range 0 4);;
putall (parties 3 (range 0 4)) 6 [];;

163
Distances.ml Normal file
View File

@ -0,0 +1,163 @@
type sommet = int;;
type poids = P of int | Inf;;
type liste_adj = (sommet*int) list array;;
type matrice_pond = poids array array;;
let rec foreach f lst = match lst with
| [] -> ()
| e::s -> f e;foreach f s;;
let adjToPond adj =
let n = Array.length adj in
let out = Array.make_matrix n n Inf in
for i=0 to n-1 do
foreach (fun (j,p) -> out.(i).(j) <- p) adj.(i)
done;
out;;
let pond2adj pond =
let n = Array.length pond in
let out = Array.make n [] in
for i=0 to n-1 do
let lst = ref [] in
for j=0 to n-1 do
match pond.(i).(j) with
| Inf -> ()
| P(p) -> lst := (j,P(p))::!lst
done;
out.(i) <- !lst
done;
out;;
let ex01 =
[|[(1,P(1));(2,P(3))];
[(0,P(1));(2,P(1));(3,P(2))];
[(0,P(3));(1,P(1));(4,P(4))];
[(1,P(2));(4,P(2));(5,P(6))];
[(2,P(4));(3,P(2));(5,P(2))];
[(3,P(6));(4,P(2))]|];;
let ex02 =
[|[(1,P(6));(2,P(9))];
[(0,P(6));(2,P(5));(3,P(8));(6,P(6))];
[(0,P(9));(1,P(5));(3,P(4));(4,P(8));(5,P(7))];
[(1,P(8));(2,P(4));(5,P(4));(6,P(5))];
[(2,P(8));(5,P(9));(7,P(4))];
[(2,P(7));(3,P(4));(4,P(9));(6,P(3));(7,P(10))];
[(1,P(6));(3,P(5));(5,P(3));(7,P(6))];
[(4,P(4));(5,P(10));(6,P(6))]|];;
let pond01 = adjToPond ex01;;
let pond02 = adjToPond ex02;;
let somme p q = match p,q with
| P(i),P(j) -> P(i+j)
| _ -> Inf;;
let inf_s p q = match p,q with
| Inf,_ -> false
| P(i),Inf -> true
| P(i),P(j) -> i<j;;
let minp p q = if (inf_s p q) then p else q;;
let copie_matrice mat =
let n = Array.length mat in
let out = Array.make n [||] in
for i=0 to n-1 do
let m = Array.length mat.(i) in
out.(i) <- (Array.make m mat.(i).(0));
for j=0 to m-1 do
out.(i).(j) <- mat.(i).(j)
done
done;
out;;
copie_matrice pond01;;
let floydWarshall pond_in =
let pond = copie_matrice pond_in in
let n = Array.length pond in
for i=0 to n-1 do
for j=0 to n-1 do
for k=0 to n-1 do
pond.(i).(j) <- minp pond.(i).(j) (somme pond.(i).(k) pond.(k).(j))
done
done
done;
pond;;
floydWarshall (pond01);;
floydWarshall (pond02);;
type couleur = Bleu | Vert;;
(** TODO à faire avec les tas **)
exception EmptyException
let mini ppq lst =
match lst with
| [] -> raise EmptyException
| e0::s ->
let rec aux lst e = match lst with
| [] -> e
| t::q -> aux q (if ppq e t then e else t) in
aux s e0;;
let ppqDrt p q = let (i,s)=p and (j,t)=q in s<=t;;
let miniIP = mini ppqDrt;;
exception NotFoundException;;
let rec removeFirst e lst = match lst with
| [] -> raise NotFoundException
| t::s -> if(e=t) then s else t::(removeFirst e s);;
let rec removeIfFirst cond lst = match lst with
| [] -> raise NotFoundException
| t::s -> if (cond t) then s else t::(removeIfFirst cond s);;
let enleveMini ppq lst =
let mm = mini ppq lst in removeFirst mm lst;;
let enleveMiniIP = enleveMini ppqDrt;;
let extractMiniIP lst = let mm = mini ppqDrt lst in (mm,removeFirst mm lst);;
let rec anymatch fn lst = match lst with
| [] -> false
| e::s -> (fn e) || anymatch fn s;;
let rec assome e lst =
let fn s = let (a,b)=s in e=a in anymatch fn lst;;
let rec updatep f k v =
(k,v)::(try (removeIfFirst (fun (a,b)->k=a) f) with NotFoundException -> []);;
let dijkstra adj e =
let f = ref [(e,0)] in
let n = Array.length adj in
let p = Array.make n (-1) in
let d = Array.make n Inf in
let cols = Array.make n Bleu in
d.(e) <- P(0);
while !f<>[] do
let (ss,rst) = extractMiniIP !f in
let (s,pp) = ss in
print_int (List.length !f);
print_endline "";
f := rst;
cols.(s) <- Vert;
foreach (fun (v,pd) -> if((inf_s d.(v) (somme d.(s) pd)) && (cols.(v)=Bleu))
then p.(v)<-s;
d.(v) <- somme d.(s) pd;
let P(pdv) = d.(v) in
f := updatep !f v pdv) adj.(s)
done;
d;;
type 'a tas = Feuille | Noeud of 'a * ('a tas) * ('a tas);;
let rec ajoute e tas = match tas with
| Feuille(u) when e<=u->Noeud(u,e,Feuille)
| Feuille(u) ->Noeud(e,u,Feuille)
| Noeud(u,p,q) when e<=u -> Noeud(u,ajoute e p,q)
| Noeud(u,p,q) -> Noeud(e,ajoute u p,q)
dijkstra ex01 2;;

99
Dunsmore.ml Normal file
View File

@ -0,0 +1,99 @@
(* Faisons des graphes ! Parce que c'est rigolo ! *)
type besoins = (int * int) array;;
let conflit s1 s2 = let (a,b)=s1 and (c,d) = s2 in b>c;;
(* I.C.B
1 5 7
/
0 3 4
/
2 6 8
*);;
let construit_graphe (s:besoins) =
let n = Array.length s in
let graphe = Array.make n [] in
for i = 0 to n-2 do
for j = i+1 to n-1 do
if conflit s.(i) s.(j) then
begin
graphe.(i) <- j::graphe.(i);
graphe.(j) <- i::graphe.(j)
end
done
done;
graphe;;
(*D1)
Les deux colorations obtenues sont:
(0,2,1,0,1,0,0) et (0,1,2,0,1,0,2,1,0).
Elles sont bien minimales car de longueur trois, et les
deux graphes contiennent un cycle de longueur 3
A-B-C-A, qui nécessite que les couleurs de
A,B et C soient distinctes deux à deux.*);;
(*D2)*)
let rec appartient l i = match l with
| [] -> false
| e::s -> (e=i)||(appartient s i) (* On prend parti de l'évaluation molle *)
;;
let plus_petit_absent l =
let rec aux l i = if appartient l i then aux l (i+1) else i in
aux l 0;;
let couleurs_voisins aretes couleurs i =
let rec aux voisins couleurs reste = match voisins with
| [] -> reste
| v::s -> aux s couleurs (if (couleurs.(v) = (-1)) then reste else (couleurs.(v)::reste))
in aux aretes.(i) couleurs [];;
let couleur_disponible aretes couleurs i =
plus_petit_absent (couleurs_voisins aretes couleurs i);;
(*E1)
G ne possède pas d'arete:
χ(G) = 1, on colorie tout de la meme couleur.
ω(G) = 1, si on peut prendre deux éléments distincts
x et y dans une clique, alors {x,y} A = .
G est un graphe complet:
χ(G) = n, on colorie tout d'une couleur différente
C'est la solution optimale car un coloriage d'un
graphe complet doit etre injectif, puisque
ij {i,j} A c(i)c(j), et donc l'image du
coloriage est nécessairement superieure à n.
ω(G) = n, car S est une clique par définition de complet.*);;
(*E2)
χ(G) ω(G)
La restriction à un sous-graphe (on enlève des sommets
et on ne garde que les arretes internes) d'un coloriage est
toujours un coloriage (car propriété universelle).
Or, considérons une clique de taille maximale C, alors le
sous-graphe associé à cette clique est complet, et donc la
restriction du coloriage à cette partie à nécessairement plus de
couleurs que la taille de la clique. Donc le coloriage original a
plus de couleurs que la taille de la plus grande des cliques. *);;
(*E3) *)
let rec inclus a b = match a with
| [] -> true
| e::s -> (appartient b e)&&(inclus s b);;
let rec est_clique arretes xs = match xs with
| [] -> true
| e::s -> (inclus s arretes.(e))&&(est_clique arretes s);;
(*II.A) (0,1,2,0,1,0,2,1,0)*)
let ex1 = [| (0,3);(1,3);(2,5);(4,7);(6,10);(8,9);(11,12)|];;
construit_graphe ex1;;

75
ENS-2006.ml Normal file
View File

@ -0,0 +1,75 @@
let n = 26;;
let lettre i = match i with
| 0 -> print_string " "
| -1 -> print_endline ""
| i -> print_string (String.make 1 (Char.chr (96+i)));;
type mot = int list;;
let imprimer motDG =
let rec aux mot = match mot with
| [] -> ()
| e::s -> aux s;lettre e in
aux motDG;
lettre (-1);;
let inverseDe motDG =
let rec aux mot motGD= match mot with
| [] -> motGD
| e::s -> aux s (e::motGD) in
aux motDG [];;
type dictTab = VideT | NoeudT of dictTab array;;
let dicoVide = VideT;;
let dicoMotVide () = let out = Array.make (n+1) VideT in out.(0) <- NoeudT(Array.make (n+1) VideT); NoeudT(out);;
let imprimerDictTab dt =
let rec aux dt prefixe = let NoeudT(arr) = dt in
for i=1 to n do
if arr.(i)!=VideT
then aux arr.(i) (i::prefixe)
done;
if arr.(0)!=VideT
then imprimer prefixe (* Faut ptet inverser *)
in match dt with
| VideT -> ()
| _ -> aux dt [];;
let rec estDansDictTab motGD dt = match dt with
| VideT -> false
| NoeudT(arr) ->
match motGD with
| [] -> arr.(0)!=VideT (* Le caractère fin de mot est dans le dico *)
| e::s -> estDansDictTab s arr.(e);;
let rec ajoutADictTab mot dt = match mot with
| [] -> dicoMotVide ()
| e::s ->
match dt with
| VideT -> let feuille = (Array.make (n+1) VideT) in
feuille.(e) <- ajoutADictTab s VideT;NoeudT(feuille)
| NoeudT(arr) ->
arr.(e) <- ajoutADictTab s arr.(e);NoeudT(arr);;
let motDG = [1;2;3];;
imprimer motDG;;
inverseDe motDG;;
let monpredico = dicoMotVide ();;
let NoeudT(x) = monpredico in
x.(5) <- dicoMotVide ();
x.(8) <- dicoMotVide ();
x.(21) <- dicoMotVide ();
let NoeudT(arr) = x.(5) in
arr.(8) <- dicoMotVide ();;
imprimerDictTab monpredico;;
estDansDictTab [5;7] monpredico;;
let monpredico2 = ajoutADictTab [5;9;9] monpredico;;
imprimerDictTab monpredico2;;

126
Glushkov.ml Normal file
View File

@ -0,0 +1,126 @@
type expr_rat =
Vide
| Epsilon
| Lettre of char
| Concat of expr_rat * expr_rat
| Plus of expr_rat * expr_rat
| Etoile of expr_rat;;
type expr_lin =
Empty
| Epsi
| Pos of int
| Prod of expr_lin * expr_lin
| Sum of expr_lin * expr_lin
| Star of expr_lin;;
let exemplE = Concat(Etoile(Plus(Lettre('a'),Concat(Lettre('a'),Lettre('b')))),Concat(Lettre('a'),Lettre('b')));;
let rec litotabi l arr i = match l with
| [] -> ()
| e::s -> arr.((Array.length arr)-i-1) <- e;
litotabi s arr (i+1);;
let linearise erat =
let rec ratisse erat i s= match erat with
| Vide -> (Empty,i,s)
| Epsilon -> (Epsi,i,s)
| Lettre(c) -> (Pos(i),i+1,c::s)
| Concat(e,f) ->
let (el1,i1,s1) = ratisse e i s in
let (el2,i2,s2) = ratisse f i1 s1 in
(Prod(el1,el2),i2,s2)
| Plus(e,f) ->
let (el1,i1,s1) = ratisse e i s in
let (el2,i2,s2) = ratisse f i1 s1 in
(Sum(el1,el2),i2,s2)
| Etoile(e) ->
let (el,ii,ss) = ratisse e i s in
(Star(el),ii,ss)
in let (elin,ii,ss) = ratisse erat 1 [] in
let assoc = Array.make (ii) ' ' in
litotabi ss assoc 0;
(elin,assoc)
;;
let rec accepteMotVide elin = match elin with
| Empty -> false
| Epsi -> true
| Pos(i) -> false
| Prod(e,f) -> (accepteMotVide e) && (accepteMotVide f)
| Sum(e,f) -> (accepteMotVide e) || (accepteMotVide f)
| Star(e) -> true;;
let rec prefixes elin = match elin with
| Empty -> []
| Epsi -> []
| Pos(i) -> [i]
| Prod(e,f) ->
if accepteMotVide e
then (prefixes e)@(prefixes f)
else (prefixes e)
| Sum(e,f) -> (prefixes e)@(prefixes f)
| Star(e) -> (prefixes e);;
let rec suffixes elin = match elin with
| Empty -> []
| Epsi -> []
| Pos(i) -> [i]
| Prod(e,f) ->
if accepteMotVide f
then (suffixes e)@(suffixes f)
else (suffixes f)
| Sum(e,f) -> (suffixes e)@(suffixes f)
| Star(e) -> (suffixes e);;
let rec suivant elin i = match elin with
| Empty -> []
| Epsi -> []
| Pos(p) -> []
| Prod(e,f) -> let ss1,ss2 = (suivant e i,suivant f i) in
let s1 = suffixes e and p2 = prefixes f in
if (List.mem i s1)
then ss1@p2@ss2
else ss1@ss2
| Sum(e,f) -> (suivant e i)@(suivant f i)
| Star(e) -> let ss = suivant e i
and p = prefixes e
and s = suffixes e in
if (List.mem i s)
then ss@p
else ss;;
type automate = {nb_etat:int;finaux:int list;transitions:((char*int) list) array};;
let transi elin assoc =
let rec transii ss assoc s = match ss with
| [] -> s
| j::ff -> transii ff assoc (((assoc.(j),j))::s)
in let n = Array.length assoc in
let out = Array.make n [] in
for i=1 to (n-1) do
out.(i) <- transii (suivant elin i) assoc []
done;
out.(0) <- transii (prefixes elin) assoc [];
out;;
let glushkov erat =
let elin,assoc = linearise erat in
let s = suffixes elin in
let momo = accepteMotVide elin in
let netats = Array.length assoc in
let transitions = transi elin assoc in
let fino = if momo then 0::s else s in
{nb_etat=netats;finaux=fino;transitions=transitions};;
let estAccepte
let (el,ccccccc) = linearise exemplE;;
accepteMotVide el;;
prefixes el;;
suffixes el;;
suivant el 1;;
glushkov exemplE;;

123
LIcorne.py Normal file
View File

@ -0,0 +1,123 @@
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.colors as colors
import time
def p(e):
print(e)
return e
def alealiste(n,M):
return np.array(np.random.random((n,))*M,dtype=int)
def ytrinsertion(L):
if len(L)<=1:
return L
out = np.empty((len(L),),dtype=int)
out[0] = L[0]
out[1:] = yield from ytrinsertion(L[1:])
for i in range(len(out)-1):
if out[i+1]>=L[0]:
out[i]=L[0]
return out
out[i] = out[i+1]
out[i+1] = L[0]
yield out
out[-1]=L[0]
yield out
def triRapideEnPlace(l,a=None,b=None):
"""
Trie la liste l entre a et b
"""
if a==None: a = 0
if b==None: b = len(l)
if b-a==0:
return l
if b-a==1:
return l
n = a+(b-a)//2
pivot = l[n]
i = n
maxindex = b
minindex = a
while maxindex != minindex:
# On souhaite ranger l'élément i dans la bonne moitié
# On suppose que i n'est pas dans les parties rangées
if l[i] < pivot or (l[i]==pivot and np.random.randint(0,2)==1):
l[i],l[minindex] = l[minindex],l[i]
minindex += 1
else:
l[i],l[maxindex-1] = l[maxindex-1],l[i]
maxindex -= 1
yield l
# On prend un i pas dans les parties triées
i = (maxindex-minindex)//2 + minindex
yield from triRapideEnPlace(l,a,maxindex)
yield from triRapideEnPlace(l,maxindex,b)
def triFusionRec(l,index):
if len(l)==0:
return l
if len(l)==1:
return l
n = len(l)//2
l1,l2 = triFusionRec(l[:n],0),triFusionRec(l[n:],n)
out = []
i,j = 0,0
while i<len(l1) or j<len(l2):
if j>=len(l2) or (i<len(l1) and l1[i]<=l2[j]):
out.append(l1[i])
i+=1
else:
out.append(l2[j])
j+=1
V[index:index+len(out+l1[i:]+l2[j:])] = np.array(out+l1[i:]+l2[j:])
print(V)
update()
return out
def update():
time.sleep(1)
N = 100
v = 100
X = np.linspace(0,N-1,N,dtype=int)
L = np.arange(N)
np.random.shuffle(L)
fig=plt.figure()
#trieur = triFusionRec(L)
V = L.copy()
barcollection = plt.bar(X,L,width=1.0)
def animate(i):
y = V
for i, b in enumerate(barcollection):
b.set_height(y[i])
b.set_color(colors.hsv_to_rgb((y[i]/v,1.0,1.0)))
import threading
class Foo (threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run (self):
ytrinsertion(V,0)
Foo().start()
anim=animation.FuncAnimation(fig,animate,repeat=False,blit=False, interval=1)
plt.show()

119
Median.ml Normal file
View File

@ -0,0 +1,119 @@
(*** Question 1 ***)
let card l =
let rec aux a n=
match a with
| [] -> n
| e::s -> aux s (n+1)
in aux l 0;;
(* Cette fonction est de complexite O(n) *)
(* En effet, la longueur de la liste parametre l de aux decroit *)
(* de un a chaque appel recursif *)
(*** Question 2 ***)
let nPetits p l =
let rec aux p l o =
match l with
| [] -> o
| e::s -> aux p s (o + (if e<p then 1 else 0))
in aux p l 0;;
(* Cette fonction est aussi de complexite O(n) *)
(* En effet, la longueur du parametre l de aux decroit *)
(* de un a chaque appel recursif *)
(*** Question 3 ***)
let partitionP p l =
let rec aux p l o =
match l with
| [] -> o
| e::s -> aux p s (if e<p then e::o else o)
in aux p l [];;
let partitionG p l =
let rec aux p l o =
match l with
| [] -> o
| e::s -> aux p s (if e>p then e::o else o)
in aux p l [];;
(* La complexite est toujours en O(n) *)
(* En effet, en counsiderant toujours la longueur de la liste *)
(* l, elle est decremente de un a chaque appel, soit *)
(* n decrementations, donc n appels en tout *)
(*** Question 4 ***)
exception NotFoundException;;
let rec elementDeRang k l = match l with
| [] -> raise NotFoundException
| e::s ->
let pets = nPetits e l in
if pets=k-1 then e
else begin
if pets>k-1
then (elementDeRang k (partitionP e s))
else (elementDeRang (k-pets-1) (partitionG e s))
end;;
(*** Question 5 ***)
(* Imaginons le pire des cas: notre pivot choisi au hazard est
à chaque fois le plus petit des éléments, et nous recherchons
le plus grand (rang=n, taille de la liste).
Alors, chaque appel à elementDeRang k l appelera successivement
nPetits l, puis partitionP ou partitionG, puis enfin elementDeRang.
Puisque nos sommes dans le pire cas, l'ensemble renvoyé par
partitionP ou partition G sera de cardinal (card(l)-1). Donc, si
on note u_n la complexité de l'appel à elementDeRang sur un
ensemble de cardinal n, on a u_n <= n+n+u_(n-1).
Ce qui donne u_n <= n*n, donc M(n) est de l'ordre de n*n *)
(*** Question 6 ***)
(*
*)
(*** Question 7 ***)
let lst = [5;4;3;2;6;8;9;7];;
card lst;;
nPetits 5 lst;;
partitionP 5 lst;;
partitionG 5 lst;;
elementDeRang 9 lst;;
(*** Question 11 ***)
type point = {x:int;y:int};;
let vect p1 p2 = {x=(p2.x) - (p1.x);y=(p2.y) - (p1.y)};;
let sgn x = if x>0 then +1 else (if x<0 then -1 else 0);;
let orientation p q r =
let pq = vect p q and pr = vect p r in
sgn ((pq.x*pr.y)-(pq.y*pr.x));;
let o={x=0;y=0} and b={x=1;y=1} and a={x=1;y=0} and c={x=0;y=1} and m={x=(-1);y=(-1)};;
orientation o a b;;
orientation o b a;;
orientation o b m;;
orientation o m a;;
orientation o m c;;
(*** Question 12 ***)
let adroite q1 q2 r1 r2 t =
((orientation r2 r1 t)>= 0) || (((orientation q1 q2 t) >= 0) && ((orientation r2 q2 t) >= 0));;
(*** Question 13 ***)
type listePoints = point list;;
type arbre =
Racine of arbre*arbre
| Noeud of point*point*point*point*arbre*arbre
| Feuille of point*point*point;;
let construire points =

356
Mysaa-Td2.ml Normal file
View File

@ -0,0 +1,356 @@
(* Exercice 1 *)
type nombre = Entier of int | Infini;;
let add a b = match a,b with
| Entier(n1),Entier(n2) -> Entier(n1+n2)
| _ -> Infini;;
let sub a b = match a,b with
| Entier(n1),Entier(n2) -> Entier(n1-n2)
| Entier(n1),Infini -> Entier(0)
| Infini,Entier(n2) -> Infini
| _ -> failwith "Indetermination";;
let mul a b = match a,b with
| Entier(n1),Entier(n2) -> Entier(n1*n2)
| _ -> Infini;;
let divE a b = match a,b with
| Entier(n1),Entier(n2) -> Entier(n1/n2)
| Entier(n1),Infini -> Entier(0)
| Infini,Entier(n2) -> Infini
| _ -> failwith "Indetermination";;
let gt a b = match a,b with
| Entier(a),Entier(b) -> a<b
| Entier(a),Infini -> false
| _ -> true;;
(* Exercice 2 *)
type 'a file = {mutable debut : 'a list; mutable fin : 'a list};;
exception EmptyException;;
exception FullException;;
let file_vide () = {debut=[];fin=[]};;
let est_vide f = f.debut=[] && f.fin=[];;
let reverse l =
let rec aux l v = match l with
| [] -> !v
| e::s -> v := e::!v;aux s v
in aux l (ref []);;
let hd f = match f with
| e::s -> e
| [] -> raise EmptyException;;
let normalise f = if f.debut=[] then begin
f.debut <- reverse f.fin;
f.fin <- []
end;;
let premier f =
normalise f;
hd f.debut;;
let enfile e f = f.fin <- e::f.fin;;
let defile f =
normalise f;
match f.debut with
| [] -> raise EmptyException
| e::s -> f.debut <- s;e;;
let x = file_vide ();;
est_vide (x);;
enfile 1 x;;
enfile 2 x;;
premier x;;
enfile 3 x;;
enfile 4 x;;
defile x;;
premier x;;
defile x;;
premier x;;
defile x;;
premier x;;
defile x;;
premier x;;
(* La complexité dans le pire des cas est O(1) pour enfile et O(n) pour defile et premier (à cause de normalise). Mais en pratique, f.debut aura rarement la valeur [] et donc defile, premier et normalise auront une complexité en O(1) *)
(* Exercice 3 *)
type 'a pile = {contenu: 'a list};;
let pilevide () = {contenu=[]};;
let est_videPile p = p.contenu=[];;
let put p e = {contenu=e::p.contenu};;
let top p = hd p.contenu;;
let behead p = match p.contenu with
| [] -> raise EmptyException
| e::s -> {contenu=s};;
type 'a file2 = {debut2: 'a pile; fin2: 'a pile};;
let file_vide2 () = {debut2=(pilevide ());fin2=(pilevide ())};;
let est_vide2 f = (est_videPile f.debut2) && (est_videPile f.fin2);;
let reverse2 p =
let rec aux l v = match l with
| [] -> !v
| e::s -> v := put !v e;aux s v
in aux p.contenu (ref (pilevide ()));;
let normalise2 f = if f.debut2=(pilevide ()) then
{debut2 = (reverse2 f.fin2);
fin2=pilevide ()}
else f;;
let premier2 f =
let x = normalise2 f in top x.debut2;;
let enfile2 e f = put f.fin2 e;;
let defile2 f =
normalise f;
match f.debut with
| [] -> raise EmptyException
| e::s -> f.debut <- s;e;;
(* Bon. La complexité est plus souvent en O(1) vu que j'ai utilisé des files et piles immuables*)
type couleur = Bleu | Rouge and assiette = couleur * int;;
let rec separer pile =
if est_videPile pile then (pilevide (),pilevide ())
else
let (c,i) = top pile in
let reste = behead pile in
let p1,p2 = separer reste in
match c with
| Bleu -> ((put p1 (c,i)),p2)
| Rouge -> (p1,(put p2 (c,i)));;
let ranger pile = let p2,p1 = separer pile in
let rec adder p1 p2 = if est_videPile p2 then p1 else
put (adder p1 (behead p2)) (top p2) in
adder p1 p2;;
let x = {contenu=[(Bleu,0);(Rouge,1);(Bleu,2);(Bleu,3);(Rouge,4);(Bleu,5);(Bleu,6);(Bleu,7);(Rouge,8);(Bleu,9);(Bleu,10);(Rouge,11);(Rouge,12);(Bleu,13)]};;
ranger x;;
(* Exercice 4 *)
type 'a arrayFile = {donnees: 'a array; mutable estVide: bool;mutable debut: int; mutable fin: int};;
(* L'utilisation du champ estVide est nécessaire afin de pouvoir différentier les files vides et pleines, qui vérifieront toutes debut=fin*)
(* On peut contourner le problème en créant un array donnees muable, qui vérifiera dont on doublera la taille lorsque la file est presque pleine. Ainsi, elle ne sera jamais pleine et le problème ne se posera pas*)
let fileVideA taille e = {donnees=Array.make taille e; estVide=true;debut=0;fin=0;};;
let estVideA f = f.estVide;;
let estPleine f = f.debut=f.fin && f.estVide=false;;
let peek f = if f.estVide then raise EmptyException else
f.donnees.(f.debut);;
let put f e = if estPleine f then raise FullException else
f.fin <- (f.fin+1) mod (Array.length f.donnees);
f.estVide <- false;
f.donnees.(f.fin) <- e;;
let head f = if estVideA f then raise EmptyException else
let x = f.donnees.(f.debut) in
f.debut <- (f.debut+1) mod (Array.length f.donnees);
f.estVide <- f.debut=f.fin;
x;;
let f = fileVideA 42 0;;
for i=1 to 42 do put f i done;;
f;;
for i=1 to 30 do print_int (head f);print_newline () done;;
for i=41 to 60 do put f i done;;
(* Exercice 5 *)
type 'a arbre = Nil | N of 'a * 'a arbre * 'a arbre;;
let rec nombre_de_noeuds abre = match abre with
| Nil -> 0
| N(e,abr1,abr2) -> 1 + (nombre_de_noeuds abr1) + (nombre_de_noeuds abr2);;
let rec nombre_de_feuilles abre = match abre with
| Nil -> 1
| N(e,abr1,abr2) -> (nombre_de_feuilles abr1) + (nombre_de_feuilles abr2);;
let rec hauteur abre = match abre with
| Nil -> 0
| N(e,abr1,abr2) -> 1 + (max (hauteur abr1) (hauteur abr2));;
let filiforme n =
let rec aux n i =
if i=n then Nil
else N(i,aux n (i+1), Nil)
(* On peut mettre i+1 si on veut indexer par [[1,n]] *)
in aux n 0;;
let rec miroir arbe = match arbe with
| Nil -> Nil
| N(e,arb1,arb2) -> N(e,miroir arb2,miroir arb1);;
let a = filiforme 10;;
nombre_de_noeuds a;;
nombre_de_feuilles a;;
hauteur a;;
miroir a;;
(* Exercice 6 *)
let parcours_infixe arbe =
let rec aux arbe lst = match arbe with
| Nil -> lst
| N(e,arb1,arb2) -> aux arb2 (e::(aux arb1 lst))
in aux arbe [];;
let parcours_prefixe arbe =
let rec aux arbe lst = match arbe with
| Nil -> lst
| N(e,arb1,arb2) -> e::(aux arb2 (aux arb1 lst))
in aux arbe [];;
let parcours_postfixe arbe =
let rec aux arbe lst = match arbe with
| Nil -> lst
| N(e,arb1,arb2) -> aux arb2 (aux arb1 (e::lst))
in aux arbe [];;
let rec aux toExplore explored = try match (defile toExplore) with
| Nil -> aux toExplore explored
| N(e,arb1,arb2) ->
begin
enfile arb1 toExplore;
enfile arb2 toExplore;
aux toExplore (e::explored)
end
with EmptyException -> explored;;
let parcours_largeur arbe =
let rec aux toExplore explored = try match (defile toExplore) with
| Nil -> aux toExplore explored
| N(e,arb1,arb2) ->
begin
enfile arb1 toExplore;
enfile arb2 toExplore;
e::(aux toExplore explored)
end
with EmptyException -> explored in
let f = file_vide () in enfile arbe f;aux f [];;
let a = N(1,N(2,N(4,N(8,Nil,Nil),N(9,Nil,Nil)),N(5,N(10,Nil,Nil),N(11,Nil,Nil))),N(3,N(6,N(12,Nil,Nil),N(13,Nil,Nil)),N(7,N(14,N(15,Nil,Nil),Nil),Nil)));;
let b = N(1,Nil,N(2,Nil,N(3,Nil,Nil)));;
(* L'infixe réagit bizarrement, mais logiquement*)
parcours_infixe a;;
parcours_prefixe a;;
parcours_postfixe a;;
parcours_largeur a;;
(* Exercice 7 *)
(* Le type arbre ne convient-t'il pas ?*)
exception NotFoundException;;
let test_abr (abre:int arbre) =
(* L'arbre est-il valide et ses noeuds compris entre a et b ? *)
let rec aux abre a b = match abre with
| Nil -> true
| N(e,abr1,abr2) -> a<=e && e<=b && (aux abr1 a e) && (aux abr2 e b)
in aux abre min_int max_int;;
let rec trouve abre n = match abre with
| Nil -> false
| N(e,abr1,abr2) -> e=n || (if e>n then trouve abr1 n else trouve abr2 n);;
let rec insere_feuille abre n = match abre with
| Nil -> N(n,Nil,Nil)
| N(e,abr1,abr2) -> if e>=n then N(e,insere_feuille abr1 n,abr2)
else N(e,abr1,insere_feuille abr2 n);;
let rec extractMax abre = match abre with
| Nil -> raise EmptyException
| N(e,a,Nil) -> a,e
| N(e,a,b) -> extractMax b;;
let rec supprime abre n = match abre with
| Nil -> raise NotFoundException
| N(e,abr1,abr2) ->
if e=n then
match abr1,abr2 with
| Nil,Nil -> Nil
| Nil,N(f,a,b) -> N(f,a,b)
| N(f,a,b),Nil -> N(f,a,b)
| a,b -> let ax,mx = extractMax a in N(mx,ax,b)
else if e>n then N(e,supprime abr1 n,abr2)
else N(e,abr1,supprime abr2 n);;
let creer_abr l =
let rec aux l a = match l with
| [] -> a
| e::s -> let na = insere_feuille a e in aux s na
in aux l Nil;;
let abre = creer_abr [25;36;41;21;33;12;28];;
supprime abre 33;;
(* Exercice 10 *)
type 'a maybe = Blank | Nope | Yep of 'a;;
let rec sizeOnScreen tol abre = match abre with
| Nil -> raise (Invalid_argument "Nil n'a pas de taille")
| N(e,Nil,Nil) -> (tol e)+1
| N(e,a,Nil) | N(e,Nil,a) -> let sa = sizeOnScreen tol a in
max ((sa/2+1)+(tol e)+3) (sa+1)
| N(e,a,b) -> let sa = sizeOnScreen tol a and sb = sizeOnScreen tol b in
max (sa+sb+2) ((tol e)+4+(sa/2)+(sb/2)+2);;
let inttol i= String.length (string_of_int i);;
sizeOnScreen inttol abre;;
let rec smul s i = match i with
| 0 -> ""
| 1 -> s
| n -> s^(smul s (i-1));;
let ( *** ) = fun (s,i) -> smul s i;;
let rec toStringTree tos abre = let tol a = String.length (tos a) in
match abre with
| Nil -> raise (Invalid_argument "Nil n'est pas affiché")
| N(e,Nil,Nil) -> (tos e)^" "
| N(e,a,Nil) ->
let astr = toStringTree a in
let asz = String.len astr in
if ((sa/2+1)+(tol e)+3)>sa then
"."***(sa/2)^"|"^("-"***((sa-(tos e))/2-1))^(tos e)^" "
else
(a/2)***"."^"|-"^(tos e)^"."***(max (sa-a/2-2-(tos e)) 1)
| N(e,Nil,b) ->
let bstr = toStringTree b in
let bsz = String.len bstr in
if ((sa/2+1)+(tol e)+3)>sa then
"."***(sa/2)^"|"^("-"***((sa-(tos e))/2-1))^(tos e)^" "
else
(a/2)***"."^"|-"^(tos e)^"."***(max (sa-a/2-2-(tos e)) 1)
| N(e,a,b) -> "";;

129
OhTomate.ml Normal file
View File

@ -0,0 +1,129 @@
type tomate = {initial: int; delta: int->char->int; est_final: int->bool};;
let deltastar i c = if (i=0) && (c='a') then 0 else 1;;
let astar = {initial= 0; delta= deltastar; est_final= (fun i -> (i=0))};;
let elang = {initial= 0; delta= (fun i c -> 1); est_final=fun i -> i=0};;
let zerolang = {initial= 0; delta= (fun i c -> 0); est_final=fun i -> false};;
let estReconnu tom s = let etat = ref tom.initial in
for i=0 to ((String.length s) -1)
do
etat := tom.delta !etat s.[i]
done;
tom.est_final !etat;;
let langTrois = {
initial=0;
delta= (fun i c -> match (i,c) with
| (0,'a') -> 1
| (1,'a') -> 2
| (2,'a') -> 2
| (2,'b') -> 3
| (3,'a') -> 2
| _ -> 42);
est_final = fun i -> (i=3)
};;
let rec ln2 i = match i with
| 0|1 -> 0
| n -> 1+(ln2 (n/2));;
let int2bin n = let s = ln2 n in
let out = String.make (s+1) '0'
and nn = ref n in
for i=0 to s do
if !nn mod 2 = 1
then Bytes.set out (s-i) '1';
nn := !nn/2
done;
out;;
let troitomate = {
initial=0;
delta= (fun i c -> match (i,c) with
| (0,'0') -> 0
| (0,'1') -> 1
| (1,'0') -> 2
| (1,'1') -> 0
| (2,'0') -> 1
| (2,'1') -> 2
| _ -> 42);
est_final = fun i -> (i=0)
};;
let divisibleParTrois n = estReconnu troitomate (int2bin n);;
(*** TESTS ***)
estReconnu astar "";;
estReconnu astar "aaa";;
estReconnu astar "a";;
estReconnu astar "abaa";;
estReconnu astar "bbb";;
estReconnu elang "";;
estReconnu elang "aa";;
estReconnu langTrois "aab";;
estReconnu langTrois "";;
estReconnu langTrois "aababababaaababaaababab";;
estReconnu langTrois "aa";;
estReconnu langTrois "aabbab";;
estReconnu langTrois "aababab";;
estReconnu langTrois "aaaab";;
estReconnu langTrois "aab";;
estReconnu langTrois "aababababaababaabaaaabaaba";;
int2bin 42;;
for i=0 to 42 do
print_string (string_of_int i);
print_string " -> ";
print_endline (string_of_bool (divisibleParTrois i))
done;;
(*** PARTIE 2***)
let rec insere e l = match l with
| [] -> [e]
| t::q -> if t<=e then e::t::q else t::(insere e q);;
let rec egal a b = match (a,b) with
| ([],[]) -> true
| (ae::a2,be::b2) -> ae=ae && (egal a2 b2)
| _ -> false;;
let rec estdans e l = match l with
| [] -> false
| t::s -> (e=t) || (not e>t) && (estdans e s);;
type totomate = {
etats: int list;
initiaux: int list;
finaux: int list;
transitions: (int*char*int) list
};;
let asastar = {
etats = [0];
initiaux = [0];
finaux = [0];
transitions = [(0,'a',0)]
};;
let eleltrans =
let rec aux l i = match i with
| 0 -> (0,(Char.chr i),1)::l
| n -> aux ((0,Char.chr n,1)::l) (n-1) in
aux [] 127;;
let elelang = {
etats= [0;1];
initiaux = [0];
finaux = [0];
transitions = eleltrans
};;
let zezerolang = {initial= 0; delta= (fun i c -> 0); est_final=fun i -> false};;

120
TD1.py Normal file
View File

@ -0,0 +1,120 @@
### Exercice 1 ###
def estDedans(l,e):
for el in l:
if e==l:
return True
return False
def maximum(l):
max = l[0]
for e in l:
if e>max:
max = e
return max
def count(l,e):
s = 0
for el in l:
if el==e:
s+=1
return s
def moyenne(l):
s = 0
for el in l:
s+=el
return s/len(l)
def var(l):
s = 0
m = moyenne(l)
for el in l:
s+=(el-m)**2
return sqrt(s/len(l))
def majoritaire(l):
cmax = 0
emax = l[0]
for el in l:
c = count(el,l)
if c > cmax:
emax = el
return emax
### Exercice 2 ###
# Structure: liste de 2-tuples contenant (volume,masse)
# Algorithme naif: on teste tout
def pasTropLourd_lourd(l,m):
selection = None #list
vmax=0
for i in range(2**len(l)):
test = [l[k] for k in range(len(l)) if ((i>>k)%2)==1]
mas = sum([t[1] for t in test])
vol = sum([t[0] for t in test])
if mas<=m and vol>vmax:
selection = test
vmax=vol
return selection
# Bernard ici présent est en O(2^n)
def pasTropLourd(l,m):
if(len(l)==0): return l
if(len(l)==1): return l if l[0][1]<=m else []
# Avec ou sans ?
reste = l[1:]
(vm,ms) = l[0]
if ms>m:
return pasTropLourd(reste,m)
else:
p1 = pasTropLourd(reste,m)
p2 = pasTropLourd(reste,m-ms)
v1 = sum([t[0] for t in p1])
v2 = sum([t[0] for t in p2])+vm
return p1 if v1>=v2 else p2+[(vm,ms)]
### Exercice 3 ###
import numpy as np
def bell(n):
bin = np.zeros((n+1,n+1),dtype=int)
bin[0,0] = 1
for i in range(1,n+1):
bin[i,0]=1
bin[i,1:] = bin[i-1,1:] + bin[i-1,:-1]
B = np.zeros((n+1,),dtype=int)
B[0] = 1
print(bin[5,:])
for i in range(1,n+1):
B[i] = np.dot(B,bin[i,:].T)
return B

42
TD2.py Normal file
View File

@ -0,0 +1,42 @@
import sys
### Exercice 1
def estDedans(el,list):
for e in list:
if e==el:
return True
return False
def index(el,list):
for i in range(len(list)):
if list[i]==el:
return i
return -1
### Exercice 3
def fibonacci(n):
if n==0:
return 0
def fib(n):
if n==1:
return (0,1)
a,b=fib(n-1)
return (b,a+b)
return fib(n)[1]
sys.setrecursionlimit(1000000000)
print(fibonacci(fibonacci(fibonacci(fibonacci(7)))))
### Exercice 4
somme = lambda f,l: sum([f(s) for s in l])
sommeRec = lambda f,l: 0 if l==0 else f(l)+sommeRec(f,l-1)
id = lambda x:x
print(sommeRec(id,42))
### Exercice 5
fact = lambda x: 1 if x==0 else x*fact(x-1)
catalan = lambda n: fact(2*n)//fact(n)//fact(n+1)

176
TD3.py Normal file
View File

@ -0,0 +1,176 @@
import os
os.chdir("/media/eleve/1B2E-2F4E/MPx/")
from piles import *
import random
import labyrinthe as laby
def copie(pile):
els = Pile()
out = Pile()
while not pile.estPileVide():
els.empiler(pile.depiler())
while not els.estPileVide():
x = els.depiler()
out.empiler(x)
pile.empiler(x)
return out
Pile.copie = copie
"""
Complexité temporelle, avec n la longueur de la pile: O(n)
Complexité spaciale, avec n la taille de la pile: O(n)
"""
def miroir(pile):
deca = pile.copie()
out = Pile()
while not deca.estPileVide():
out.empiler(deca.depiler())
return out
Pile.miroir = miroir
"""
O(n)
O(n)
"""
def taille(pile):
deca = pile.copie()
i = 0
while not deca.estPileVide():
i+=1
deca.depiler()
return i
Pile.taille = taille
"""
O(n)
O(n)
"""
def nth(pile,n):
t = pile.taille()
deca = pile.copie()
i = 0
while not deca.estPileVide():
i+=1
if i==t-n:
return deca.depiler()
deca.depiler()
raise IndexError("La pile est trop petite !")
Pile.nth = nth
"""
O(n)
O(n)
"""
def degringoler(pile):
if pile.estPileVide():
raise IndexError("Mais ……… cette pile est vide !")
x0 = pile.depiler()
deca = Pile()
while not pile.estPileVide():
deca.empiler(pile.depiler())
pile.empiler(x0)
while not deca.estPileVide():
pile.empiler(deca.depiler())
Pile.degringoler = degringoler
"""
O(exp(42*n)) non, bien sur, c'est du O(n)
O(n)
"""
def toList(pile):
deca = pile.copie()
out=[]
while not deca.estPileVide():
out.append(deca.depiler())
return out
Pile.toList = toList
print("----------------------------")
print("Essai de la (nouvelle) classe pile")
p = Pile()
p.empiler(1)
p.empiler(2)
print(p)
p.depiler()
print(p)
p.depiler()
print(p)
p.empiler('*')
p.empiler('p')
p.empiler('m')
print(p)
print(p.nth(0))
print(p.nth(1))
print(p.nth(2))
print(p.miroir())
p.empiler(1)
print(p)
print("----------------------------")
### Labyrinthes
def estValide(i,j,n,p):
return (0<=i and i<n) and (0<=j and j<p)
def initList(n,p):
out = []
for _ in range(n):
out.append(p*[False])
return out
def initNList(n,p):
out = []
for _ in range(n):
out.append(p*[None])
return out
def voisins(case,n,p,dejaVu):
i,j = case
out = [(i-1,j),(i,j-1),(i,j+1),(i+1,j)]
return [(i,j) for i,j in out if estValide(i,j,n,p) and not dejaVu[i][j]]
def choix(L):
if(len(L)==0):
raise IndexError("Un élément du vide ? Je propose néant mais vous n'allez pas aimer.")
return L[random.randrange(len(L))]
def labyrinthe(n,p):
dejaVu = initList(n,p)
predecesseur = initNList(n,p)
pile = Pile()
pile.empiler((0,0))
segs = Pile()
while not pile.estPileVide():
caseCourante=pile.depiler()
vz = voisins(caseCourante,n,p,dejaVu)
if not len(vz)==0:
nouvelleCase = choix(vz)
(inn,jnn) = nouvelleCase
dejaVu[inn][jnn] = True
segs.empiler((caseCourante,nouvelleCase))
predecesseur[inn][jnn] = caseCourante
pile.empiler(caseCourante)
pile.empiler(nouvelleCase)
return segs.toList(),predecesseur
def plusCourtParfait(l,pdz,dest):
path = Pile()
pile.empile(out)
whereami = dest
while
l,pdz = labyrinthe(100,100)
laby.affiche(l,100,100)

112
Tritritritri .py Normal file
View File

@ -0,0 +1,112 @@
import numpy as np
tl = (np.array(np.random.rand(20)*100,dtype=int))
def triInsertion(l):
out = []
for e in l:
toadd = e
nout = []
for i in range(len(out)):
if out[i]>=toadd:
nout.append(toadd)
toadd=out[i]
else:
nout.append(out[i])
nout.append(toadd)
out = nout
return out
def triFusionRec(l):
if len(l)==0:
return l
if len(l)==1:
return l
n = len(l)//2
l1,l2 = triFusionRec(l[:n]),triFusionRec(l[n:])
out = []
i,j = 0,0
while i<len(l1) or j<len(l2):
if j>=len(l2) or (i<len(l1) and l1[i]<=l2[j]):
out.append(l1[i])
i+=1
else:
out.append(l2[j])
j+=1
return out
def triRapideRec(l):
if len(l)==0:
return l
if len(l)==1:
return l
n = np.random.randint(0,len(l))
pivo = l[n]
epivot,pppivot,pgpivot = [],[],[]
for e in l:
if e==pivo:
epivot.append(e)
elif e<pivo:
pppivot.append(e)
else:
pgpivot.append(e)
return triRapideRec(pppivot)+epivot+triRapideRec(pgpivot)
def triRapideEnPlace(l,a=None,b=None):
"""
Trie la liste l entre a et b
"""
if a==None: a = 0
if b==None: b = len(l)
if b-a==0:
return l
if b-a==1:
return l
n = a+(b-a)//2
pivot = l[n]
i = n
maxindex = b
minindex = a
while maxindex != minindex:
# On souhaite ranger l'élément i dans la bonne moitié
# On suppose que i n'est pas dans les parties rangées
if l[i] < pivot or (l[i]==pivot and np.random.randint(0,2)==1):
l[i],l[minindex] = l[minindex],l[i]
minindex += 1
else:
l[i],l[maxindex-1] = l[maxindex-1],l[i]
maxindex -= 1
# On prend un i pas dans les parties triées
i = (maxindex-minindex)//2 + minindex
l = triRapideEnPlace(l,a,maxindex)
l = triRapideEnPlace(l,maxindex,b)
return l
def triFusionEnPlace(l,a=None,b=None):
"""
Trie la liste l entre a et b
"""
if a==None: a = 0
if b==None: b = len(l)
if b-a==0:
return l
if b-a==1:
return l
n = a + (b-a)//2
l = triFusionEnPlace(l,a,n)
l = triFusionEnPlace(l,n,b)
i = a
j = n
midmax = l[n-1]
while i<n-a and j<b-n
def multitest():
for _ in range(1000):
tl = (np.array(np.random.rand(20)*100,dtype=int))
print(tl)
assert (triInsertion(tl)==triRapideEnPlace(tl)).all()

42
adn.py Normal file
View File

@ -0,0 +1,42 @@
import numpy as np
def moyenne(X):
return sum(X)/len(X)
def variance(X):
m = moyenne(X)
return sum([x**2 for x in X]) - (moyenne(X))**2
def somme(X):
if(isinstance(X,(int,float,np.int64))):
return X
return sum([somme(x) for x in X])
print(somme(np.array([0,3,4,54])))
def seuillage(A,seuil):
filtre = lambda x,s: 0 if x<s else 1
return np.vectorize(filtre)(A,seuil)
def pixel_centre_bille(A):
idx = np.indices(A.shape)*A
return [(somme(idx[i])/somme(A)) for i in (0,1)]
def prendre_photo():
return np.random.rand(256,256)
def positions(n,seuil):
return [pixel_centre_bille(seuillage(prendre_photo(),seuil)) for _ in range(n)]
def fluctuations(P,t):
pass
table = np.random.rand(12,12)
table2=np.eye(12,12)
seuillé = seuillage(table,0.7)
print(table)
print(seuillage(table,0.7))
print(pixel_centre_bille(seuillé))
print(positions(42,0.6))

102
bédédé.py Normal file
View File

@ -0,0 +1,102 @@
#I.1
def SelectionConstante(table,indice,constante):
sortie = []
for enregistrement in table:
if(enregistrement[indice]==constante):
sortie.append(enregistrement)
return sortie
#I.2
# Ce programme est de complexité O(n) avec n la taille de la table. En effet, toutes les instructions sont en temps constant et la boucle parcours chacun des n éléments de la table une et une seule fois.
#I.3
def SelectionEgalité(table,indice1,indice2):
sortie = []
for enregistrement in table:
if(enregistrement[indice1]==enregistrement[indice2]):
sortie.append(enregistrement)
return sortie
#I.4
def ProjectionEnregistrement(enregistrement,listeIndices):
newregistrement = []
for i in listindices:
newregistrement.append(enregistrement[i])
return newregistrement
#I.5
def Projection(table, listeIndices):
sortie = []
for enregistrement in table:
sortie.append(ProjectionEnregistrement(enregistrement))
return sortie
#I.6
def ProduitCartesien(table1,table2):
sortie = []
for enreg1 in table1:
for enreg2 in table2:
sortie.append(enreg1+enreg2)
return sortie
#I.7
def jointEnregistrementsSaufIndice(enreg1,enreg2,indice2):
sortie = [] + enreg1
for i in range(0,indice2):
sortie.append(enreg2[i])
for i in range(indice2+1,len(enreg2)):
sortie.append(enreg2[i])
return sortie
def Jointure(table1,table2,indice1,indice2):
sortie = []
for enreg1 in table1:
for enreg2 in table2:
if(enreg1[indice1]==enreg2[indice2]):
sortie.append(jointEnregistrementsSaufIndice(enreg1,enreg2,indice2))
return sortie
#I.8
# La complexité est en O(n1*n2*(k2-1))
# En effet, la fonction jointEnregistrementSaufIndice effectue une copie de l'enregistrement (copie = somme avec la liste vide) en temps constant, puis deux boucles qui s'executent respectivement (indice1) et (k2-indice1-1), donc une complexité pour cette fonction en O(k2-1)
# Enfin, la fonction Jointure est constituée d'une instruction en temps constant, de deux boucles imbriquées s'executant respectivement n1 et n2 fois. Le contenu de la boucle est en complexité O(1 ou k2-1) donc dans le pire des cas, O(k2-1) d'où la complexité donnée.
#I.9
def egal(liste1,liste2):
if(len(liste1) != len(liste2)):
return False
for i in range(len(liste1)):
if(liste1(i)==liste2(i)):
return False
return True
def SupprimerDoublons(table):
sortie = []
for ei in range(len(table)):
oups = False
for eii in range(ei):
if(egal(table[ei],table[eii])):
oups = True
if(not oups):
sortie.append(table[ei])
return sortie
#I.10
# La fonction égal est de complexité (dans le pire des cas) O(n*n) avec n la longeur commune des deux liste (on peut considérer n'importe laquelle des deux, puisque si l'une est plus longue que l'autre, le coût sera constant).
# La fonctions SupprimerDoublons effectue deux boucles s'executant n (longeur de la table) fois pour la première et ei pour la deuxième. Le tout s'execute donc 1+2+3+…+n fois , c'est à dire environ n*n/2.
# La fonction egal étant appelé à chaque fois sur des liste de taille k, l'arité de la table, la complexité totale est donc en O(n*n/2*k)

42
euler.py Normal file
View File

@ -0,0 +1,42 @@
import numpy as np
import matplotlib.pyplot as pplt
def euler(f, y0, T):
Y = [y0]
for i in range(1,len(T)):
dt = T[i]-T[i-1]
Y.append(Y[-1]+dt*f(Y[-1],dt))
if(Y[-1][0]<0):
return Y
return Y
# Y = [z,z',y,y']
T = np.linspace(0,10,10000,dtype=np.float)
g = 9.81
alpha = 1
me = 63
qe = 1
B = 0.1
def equadiff(Y,dt):
z,zp,y,yp = Y
nzpp = - alpha/me*zp*zp - qe*B/me*yp - g
nypp = - alpha/me*yp*yp - qe*B/me*zp
nzp = zp + dt*nzpp
nyp = yp + dt*nypp
return np.array([nzp,nzpp,nyp,nypp],dtype=np.float)
Y = euler(equadiff,np.array([1000,0,0,0],dtype=np.float),T)
Tt = T[:len(Y)]
Yy = [y[0] for y in Y]
Zz = [y[2] for y in Y]
#pplt.plot(Tt,Yy)
#pplt.plot(Tt,Zz)
pplt.plot(Zz,Yy)
pplt.show()

41
labyrinthe.py Normal file
View File

@ -0,0 +1,41 @@
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
def affiche(segments, n, p, anim=False):
"""affiche les segments de la liste segments d'une grille n x p
avec éventuelle animation"""
# graphe orthonormé sans axe
plt.axis('off')
plt.axis('equal')
plt.axis([-1, n + 1, -1, p + 1])
# Affichage du fond
plt.fill([-1, -1, n, n], [-1, p, p, -1], 'gray', lw=0)
# Affichage du labyrinthe
affiche_couleur(segments, n, p, 'w', anim)
def affiche_couleur(segments, n, p, couleur, anim=False):
"""affichage des segments avec couleur"""
largeur_trait = 150 / max(n, p)
# affichage d'un départ
plt.plot([-1, 0], [0, 0], color=couleur, lw=largeur_trait)
# affichage des segments
for P1, P2 in segments:
x1, y1 = P1
x2, y2 = P2
plt.plot([x1, x2], [y1, y2], color=couleur, lw=largeur_trait)
if anim:
plt.pause(1e-6)
# affichage d'une arrivée
plt.plot([n, n - 1], [p - 1, p - 1], color=couleur, lw=largeur_trait)
# pause à la place de show permet d'éventuelles animations
plt.pause(1e-6)
# Enregistrement dans un fichier
plt.savefig('laby_{}.png'.format(couleur))

51
piles.py Normal file
View File

@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
class Pile(object):
def __init__(self):
self.pile = []
def estPileVide(self):
return self.pile == []
def empiler(self, x):
self.pile.append(x)
def depiler(self):
if self.estPileVide():
raise ValueError("pile vide")
return self.pile.pop()
def sommet(self):
res = self.depiler()
self.empiler(res)
return res
def affiche(self):
res = "sommet -> "
i = len(self.pile)-1
while i >= 0:
res += str(self.pile[i])+" | "
i -= 1
return res
# la fonction suivante permet une utilisation de print avec une pile
def __repr__(self):
return self.affiche()
print("----------------------------------------------------------------")
print("Essai de la classe pile")
p = Pile()
p.empiler(1)
p.empiler(2)
p.affiche()
p.depiler()
p.affiche()
p.depiler()
p.affiche()
p.empiler('*')
p.empiler('p')
p.empiler('m')
print(p)
p.empiler(1)
print(p)
print("----------------------------------------------------------------")