From 45beede2b82f5e987f9edfa5f4757b322ee78059 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20de=20Favereau?= <jerome.defavereau@uclouvain.be> Date: Wed, 30 Sep 2020 08:51:28 +0200 Subject: [PATCH] Update ex3.py : add alternate solution without find (not seen in course). --- Chapter_3/ex3.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/Chapter_3/ex3.py b/Chapter_3/ex3.py index 845ddf2..bf99c0d 100644 --- a/Chapter_3/ex3.py +++ b/Chapter_3/ex3.py @@ -1,4 +1,3 @@ - txt="Les objectifs de Python en font un langage pedagogique ideal.C'est un langage general-purpose:il s'adapte a toutes les applications" seperatorList = " ,.;-'\":\n/\\?+()’!°" @@ -22,3 +21,25 @@ while len(txt) > 0: txt="" print("Il y a {0} mots dans la phrase.".format(n_words)) + +# solution alternative sans utiliser "find" +# moins optimale sur de grands textes + +in_word = False +words = [] +curword = "" + +for letter in txt: + if letter in separators: + if in_word: + words.append(curword) + curword = "" + in_word = False + else: + in_word = True + curword += letter + +if in_word: + words += curword + +print("il y a", len(words), "mot(s)") \ No newline at end of file -- GitLab