TP Tri Rech
TP Tri Rech
def recherche_indice_max(L,i):
ind_max=0
for j in range(i):
if L[j]>L[ind_max]:
ind_max=j
return ind_max
def tri_selection(L):
n=len(L)
for i in range(n-1,0,-1):
ind_max=recherche_indice_max(L,i)
if ind_max!=i:
L[i],L[ind_max]=L[ind_max],L[i]
def tri_insertion(L):
n=len(L)
for i in range(1,n):
pos=i
while L[pos-1]>L[i] and pos >0:
pos=pos-1
#print(pos)
elt=L[i]
for j in range(i,pos,-1):
L[j]=L[j-1]
L[pos]=elt
L = []
c = eval(input("Choisir le tri à appliquer : \n1 - tri par bulle\n2 - tri par insertion\n3
if c == 1 :
tri_par_bulle(L)
elif c == 2 :
tri_selection(L)
elif c == 3 :
tri_insertion(L)
else :
print("choix invalide")
print(L)
Exercice 2
In [7]: def tri(L,croissant):
n=len(L)
for i in range(1,n):
pos=i
while L[pos-1]>L[i] and pos >0:
pos=pos-1
#print(pos)
elt=L[i]
for j in range(i,pos,-1):
L[j]=L[j-1]
L[pos]=elt
if not croissant :
L.reverse()
Exercice 3 :
In [10]: alpha = list("abcdefghijklmnopqrstuvwxyz")
def motSup(M1,M2):
l = list(M1)
p = list(M2)
m = min(len(l),len(p))
for i in range(m):
if alpha.index(l[i]) > alpha.index(p[i]) :
return True
elif alpha.index(l[i]) < alpha.index(p[i]) :
return False
else :
continue
return True
motSup("batch","application")
True
Out[10]:
Exercice 4 :
In [17]: def initP(L):
m = max(L)
P = []
for i in range(m+1):
x = L.count(i)
P.append(x)
return P
initP([1,25,3,1,3])
[0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
Out[17]:
[0, 1, 1, 1, 1, 1, 1]
[1, 2, 3, 4, 5, 6]
exercice 5 :
In [41]: def rechDichorec(L,x,d,f):
if d>f:
return False
else :
m = (d + f+1 ) // 2
if x > L[m]:
return rechDichorec(L,x,m+1,f)
elif x < L[m] :
return rechDichorec(L,x,d,m-1)
else :
return True
def rechDicho(L,x):
tri_selection(L)
print(L)
d = 0
f = len(L)-1
return rechDichorec(L,x,d,f)
In [47]: L = [1,2,4,8,5,3,1,6,7,9,5]
print(rechDicho(L,6))
[1, 1, 2, 3, 4, 5, 7, 5, 6, 8, 9]
True
In [ ]: