Académique Documents
Professionnel Documents
Culture Documents
Q1
In [5]:
def echange(tab, i, j):
x=tab[i]
tab[i]=tab[j]
tab[j]=x
return tab
In [6]:
L=[1,5,9,6,7,2]
echange(L,1,4)
Out[6]:
[1, 7, 9, 6, 5, 2]
Q2
In [7]:
def est_trie(T):
for i in range(len(T)-1):
if T[i]>T[i+1]:
return False
return True
In [8]:
est_trie([1,2,3,5])
Out[8]:
True
Q2
In [9]:
def indice_min(tab, i):
i_mini = i
for j in range(i , len(tab)):
if tab[j] < tab[i_mini]:
i_mini = j
return i_mini
In [10]:
indice_min([1,2,3,7,4,2],2)
Out[10]:
5
Q3
Q3
In [11]:
def tri_selection(tab):
for i in range(len(tab)):
echange(tab, i, indice_min(tab, i))
return tab
In [12]:
tri_selection([5,9,3,4,1])
Out[12]:
[1, 3, 4, 5, 9]
Le Tri à bulles
Q2
In [13]:
def passage(tab, fin):
for i in range(fin - 1):
if tab[i] > tab[i + 1]:
echange(tab, i, i + 1)
return tab
Q3
In [14]:
def tri_bulles(tab):
fin = len(tab)
while not est_trie(tab):
passage(tab,fin)
return tab
In [15]:
tri_bulles([4,5,3,2,9])
Out[15]:
[2, 3, 4, 5, 9]
Q2
In [24]:
def insere(tab, i):
k = i
while k > 0 and tab[k - 1] > tab[k]:
echange(tab, k - 1, k)
k -= 1
return tab
In [25]:
insere([2,4,5,8,3,1], 4)
Out[25]:
[2, 3, 4, 5, 8, 1]
Q3
In [28]:
def tri_insertion(tab):
for i in range(len(tab)):
insere(tab, i)
return tab
In [29]:
tri_insertion([5,9,3,4,1])
Out[29]:
[1, 3, 4, 5, 9]
La Recherche
Q1
In [30]:
def recherche_sequentielle(liste, element):
for x in liste:
if x == element:
return True
return False
Q2
In [34]:
def recherche_dichotomique(liste, element):
debut = 0
fin = len(liste) - 1
return False
In [35]:
recherche_dichotomique([1,3,6,9,20,25],3)
Out[35]:
True
In [ ]:
def recherche_dichotomique_recursive(liste, element):
if len(liste) == 0:
return False
milieu = len(liste) // 2
if liste[milieu] == element:
return True
elif liste[milieu] < element:
return recherche_dichotomique_recursive(liste[milieu+1:], element)
else:
return recherche_dichotomique_recursive(liste[:milieu], element)