Aller au contenu

4.1 Extremums et moyennes⚓︎

image

1. Algorithme de recherche de maximum⚓︎

Recherche de maximum ❤

🐍 Script Python
def recherche_max(tab):
    '''renvoie le maximum de la liste tab'''
    maxi = tab[0]           # (1)
    for elt in tab:
        if elt > maxi:
            maxi = elt
    return maxi
  1. On initialise le maximum avec la première valeur du tableau (surtout pas avec 0 ou «moins l'infini» !)

Utilisation :

🐍 Script Python
>>> recherche_max([4, 3, 8, 1])
  8

2. Algorithme de calcul de moyenne⚓︎

Calcul de moyenne ❤

🐍 Script Python
def moyenne(tab):
    ''' renvoie la moyenne de tab'''
    somme = 0
    for elt in tab:
        somme += elt
    return somme / len(tab)

Utilisation :

🐍 Script Python
>>> moyenne([4, 3, 8, 1])
  4.0

3. Algorithme de recherche d'occurrence⚓︎

Recherche d'occurrence ❤

🐍 Script Python
def recherche_occurrence(elt, tab):
    ''' renvoie la liste (éventuellement vide)
    des indices de elt dans tab'''
    liste_indice = []
    for i in range(len(tab)):
        if tab[i] == elt:
            liste_indice.append(i)
    return liste_indice

Recherche d'occurrence avec While ❤

🐍 Script Python
def recherche(liste, element) :
    i=0
    while  i<len(liste) and liste[i]!=element:
        i += 1
    if (i<len(liste) and liste[i]==element):
        return True
    else : return False
#Autre solution en utilisant un booleen 
def recherche2(liste, element):
    i=0
    trouve=False
    while i<len(liste) and not trouve:
        if liste[i]==element:
            trouve=True
            break
        i = i + 1
    return trouve

Utilisation :

🐍 Script Python
>>> recherche_occurrence(3, [1, 6, 3, 8, 3, 2])
[2, 4]
>>> recherche_occurrence(7, [1, 6, 3, 8, 3, 2])
[]