Nombre d'exclamations consécutives !!!⚓︎
Dans une phrase !!! écrite !!! certains utilisateurs abusent des points d'exclamations !! Ce pour différentes raisons ! Bref.
Écrire une fonction nb_max_consecutifs
qui prend un caractère motif
(une chaine de caractères de longueur 1), et une chaine de caractères phrase
à analyser. La fonction renvoie le nombre maximal d'occurrences consécutives de motif
dans phrase
.
Exemples
>>> phrase = "Dans une phrase !!! écrite !!! certains utilisateurs abusent des points d'exclamations !! Ce pour différentes raisons ! Bref."
>>> nb_max_consecutifs("!", phrase)
3
>>> phrase = "Un mot puis un autre avec espaces."
>>> nb_max_consecutifs(" ", phrase)
8
>>> expression = "((2 * x + 3) / (x + 1))"
>>> nb_max_consecutifs("(", expression)
2
>>> nb_max_consecutifs("-", expression)
0
def nbpy-undmaxpy-undconsecutifs(motif, phrase):bksl-nl ...bksl-nlbksl-nlbksl-nlbksl-nlbksl-nl# testsbksl-nlbksl-nlphrase = "Dans une phrase !!! écrite !!! certains utilisateurs abusent des points d'exclamations !! Ce pour différentes raisons ! Bref."bksl-nlassert nbpy-undmaxpy-undconsecutifs("!", phrase) == 3bksl-nlbksl-nlphrase = "Un mot puis un autre avec espaces."bksl-nlassert nbpy-undmaxpy-undconsecutifs(" ", phrase) == 8bksl-nlbksl-nlexpression = "((2 py-str x + 3) / (x + 1))"bksl-nlassert nbpy-undmaxpy-undconsecutifs("(", expression) == 2bksl-nlassert nbpy-undmaxpy-undconsecutifs("-", expression) == 0bksl-nlbksl-nldef nbpy-undmaxpy-undconsecutifs(motif, phrase):bksl-nl nbpy-undmax = 0bksl-nl nbpy-undcourant = 0bksl-nl for caractere in phrase:bksl-nl if caractere == motif:bksl-nl nbpy-undcourant += 1bksl-nl if nbpy-undcourant > nbpy-undmax:bksl-nl nbpy-undmax = nbpy-undcourantbksl-nl else:bksl-nl nbpy-undcourant = 0bksl-nl return nbpy-undmaxbksl-nlbksl-nlbksl-nl# testsbksl-nlbksl-nlphrase = "Dans une phrase !!! écrite !!! certains utilisateurs abusent des points d'exclamations !! Ce pour différentes raisons ! Bref."bksl-nlassert nbpy-undmaxpy-undconsecutifs("!", phrase) == 3bksl-nlbksl-nlphrase = "Un mot puis un autre avec espaces."bksl-nlassert nbpy-undmaxpy-undconsecutifs(" ", phrase) == 8bksl-nlbksl-nlexpression = "((2 py-str x + 3) / (x + 1))"bksl-nlassert nbpy-undmaxpy-undconsecutifs("(", expression) == 2bksl-nlassert nbpy-undmaxpy-undconsecutifs("-", expression) == 0bksl-nlbksl-nl
A
- On initialise le nombre d'occurrences maximal ainsi que le courant, tous deux à zéro.
- On fait une boucle, sans avoir besoin de l'indice,
- si le caractère correspond au motif, on incrémente le compteur courant, et on met à jour si nécessaire le maximum provisoire,
- sinon on remet le compteur courant à 0
Z