From 9657a82d8daf64aba831ecad269ae487da00ec39 Mon Sep 17 00:00:00 2001 From: Cacahuete Date: Sat, 12 Dec 2020 16:14:39 +0100 Subject: [PATCH] count: added v3 and v4 after reading about Trey's solution. --- count/count.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/count/count.py b/count/count.py index 484f53f..ef0202d 100644 --- a/count/count.py +++ b/count/count.py @@ -1,5 +1,5 @@ import re -from collections import defaultdict +from collections import defaultdict, Counter def count_words_v1(sentence): @@ -17,4 +17,18 @@ def count_words_v2(sentence): return count -count_words = count_words_v2 +def count_words_v3(sentence): + """Augmented by trey's regex.""" + regex = r"\b[\w'-]+\b" + count = defaultdict(int) + for word in re.findall(regex, sentence): + count[word.lower()] += 1 + return count + + +def count_words_v4(sentence): + """And the most compact yet pythonic solution.""" + return Counter(re.findall(r"\b[\w'-]+\b", sentence.lower())) + + +count_words = count_words_v4