Solution Exercice 77: algorithme python permettant de chercher une occurrence

Exercice 77

Écrire un algorithme Python qui détermine le premier index d'une occurrence existante dans une chaîne donnée s sans utiliser de méthode prédéfinie comme find() ou rfind() ...
L'algorithme doit renvoyer -1 si l'occorrence n'existe pas dans la chaîne s .
Exemple: si s = "langage de programmation Python" et occ = "prog" l'algorithme renvoie 7

Solution





# coding:utf-8
def findFirstOccurrence(s , occ):
    # obtenir les longueurs des chaines occ et s 
    m = len(occ)
    n = len(s)

    # initialisation de lindex 
    index = -1
    # recherche de l'occurrence dans la chaîne s
    for i in range(0 , n-m):
        if s[i : m + i] == occ:
            index = i
            break
    return index

# Exemple:
s = "Python programming language"
occ1 = "prog"
occ2 = "algorithm"
print(findFirstOccurrence(s, occ1)) # affiche: 7
print(findFirstOccurrence(s, occ2)) # affiche: -1




 

 

Younes Derfoufi
CRMEF OUJDA

1 thought on “Solution Exercice 77: algorithme python permettant de chercher une occurrence

Leave a Reply to TP Python: Exercices corrigés d’algorithmique Python – Les bases | Cours Python Très Facile Cancel reply

Your email address will not be published. Required fields are marked *