From 967d5fafc68cc8e057ffa03ea4d94b3170c1fe87 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:47:53 -0500 Subject: [PATCH 1/9] Add files from old draft PR Co-Authored-By: BethanyG --- .../word-count/.approaches/config.json | 56 +++ .../filter-with-counter/content.md | 19 + .../filter-with-counter/snippet.txt | 8 + .../word-count/.approaches/introduction.md | 342 ++++++++++++++++++ .../str-iteration-with-dict/content.md | 23 ++ .../str-iteration-with-dict/snippet.txt | 8 + .../str-replace-with-collections/content.md | 50 +++ .../str-replace-with-collections/snippet.txt | 8 + .../content.md | 36 ++ .../snippet.txt | 8 + .../str-replace-with-dict/content.md | 31 ++ .../str-replace-with-dict/snippet.txt | 8 + .../str-translate-with-counter/content.md | 23 ++ .../str-translate-with-counter/snippet.txt | 7 + .../using-the-re-module/content.md | 57 +++ .../using-the-re-module/snippet.txt | 7 + .../practice/word-count/.articles/config.json | 11 + .../.articles/performance/code/Benchmark.py | 0 .../.articles/performance/content.md | 0 .../.articles/performance/snippet.md | 0 20 files changed, 702 insertions(+) create mode 100644 exercises/practice/word-count/.approaches/config.json create mode 100644 exercises/practice/word-count/.approaches/filter-with-counter/content.md create mode 100644 exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt create mode 100644 exercises/practice/word-count/.approaches/introduction.md create mode 100644 exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md create mode 100644 exercises/practice/word-count/.approaches/str-iteration-with-dict/snippet.txt create mode 100644 exercises/practice/word-count/.approaches/str-replace-with-collections/content.md create mode 100644 exercises/practice/word-count/.approaches/str-replace-with-collections/snippet.txt create mode 100644 exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md create mode 100644 exercises/practice/word-count/.approaches/str-replace-with-comprehensions/snippet.txt create mode 100644 exercises/practice/word-count/.approaches/str-replace-with-dict/content.md create mode 100644 exercises/practice/word-count/.approaches/str-replace-with-dict/snippet.txt create mode 100644 exercises/practice/word-count/.approaches/str-translate-with-counter/content.md create mode 100644 exercises/practice/word-count/.approaches/str-translate-with-counter/snippet.txt create mode 100644 exercises/practice/word-count/.approaches/using-the-re-module/content.md create mode 100644 exercises/practice/word-count/.approaches/using-the-re-module/snippet.txt create mode 100644 exercises/practice/word-count/.articles/config.json create mode 100644 exercises/practice/word-count/.articles/performance/code/Benchmark.py create mode 100644 exercises/practice/word-count/.articles/performance/content.md create mode 100644 exercises/practice/word-count/.articles/performance/snippet.md diff --git a/exercises/practice/word-count/.approaches/config.json b/exercises/practice/word-count/.approaches/config.json new file mode 100644 index 0000000000..9c72ccbccd --- /dev/null +++ b/exercises/practice/word-count/.approaches/config.json @@ -0,0 +1,56 @@ +{ + "introduction": { + "authors": ["bethanyg"] + }, + "approaches": [ + { + "uuid": "a3dd190d-ff92-4190-b8aa-2b4b46171b46", + "slug": "str-iteration-with-dict", + "title": "String Iteration with Dictionary", + "blurb": "Iterate over the sentence to filter out punctuation and sum word counts with a dict.", + "authors": ["bethanyg"] + }, + { + "uuid": "5a5f4f89-b016-48ed-9316-a49cadf9735f", + "slug": "str-replace-with-dict", + "title": "String Replace with Dictionary", + "blurb": "Use str.replace and str.strip to filter out punctuation and sum word counts with a dict.", + "authors": ["bethanyg"] + }, + { + "uuid": "3d5d629f-58b6-43c5-9470-30b30b193892", + "slug": "str-replace-with-comprehensions", + "title": "String Replace with Comprehensions", + "blurb": "Use str.replace and str.strip to filter out punctuation and sum word counts with comprehensions.", + "authors": ["bethanyg"] + }, + { + "uuid": "373182b1-8d21-4ee6-aa49-94ff6a9c57a1", + "slug": "str-replace-with-collections", + "title": "String Replace with Collections", + "blurb": "Use str.replace and str.strip to filter out punctuation and let collections.Counter do the rest.", + "authors": ["bethanyg"] + }, + { + "uuid": "2afed504-500d-4415-a507-b78311bde777", + "slug": "using-the-re-module", + "title": "Using the Re Module", + "blurb": "Python's Re module is both versatile and powerful.", + "authors": ["bethanyg"] + }, + { + "uuid": "0aa44eec-1c71-4937-8e3f-c45cbba22cc1", + "slug": "str-translate-with-counter", + "title": "String Translate with Counter", + "blurb": "Use str.translate to filter out punctuation and then tally words with collections.Counter.", + "authors": ["bethanyg"] + }, + { + "uuid": "182463b2-fcfa-4445-967c-8b185b7853c9", + "slug": "filter-with-counter", + "title": "Filter with Counter", + "blurb": "Use the built-in filter function to clean the sentence and collections.Counter to count the words.", + "authors": ["bethanyg"] + } + ] +} \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/filter-with-counter/content.md b/exercises/practice/word-count/.approaches/filter-with-counter/content.md new file mode 100644 index 0000000000..3ff0b8ce8a --- /dev/null +++ b/exercises/practice/word-count/.approaches/filter-with-counter/content.md @@ -0,0 +1,19 @@ +# Filter with Counter + + +```python +from collections import Counter +import string + +def count_words(sentence): + words = filter(None, (word.strip(string.punctuation) + for word in sentence + .lower() + .replace("_"," ") + .replace(",", " ") + .split()) + ) + return Counter(words) +``` + + diff --git a/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt b/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt new file mode 100644 index 0000000000..db209ab074 --- /dev/null +++ b/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt @@ -0,0 +1,8 @@ +def count_words(sentence): + words = filter(None, (word.strip(string.punctuation) + for word in sentence.lower() + .replace("_"," ") + .replace(",", " ") + .split())) + + return Counter(words) \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/introduction.md b/exercises/practice/word-count/.approaches/introduction.md new file mode 100644 index 0000000000..53624ae6e6 --- /dev/null +++ b/exercises/practice/word-count/.approaches/introduction.md @@ -0,0 +1,342 @@ +# Introduction + +There are many Pythonic ways to solve the Word Count exercise. +Among them are: + +- String iteration with `dict.get()` +- Using `str.replace()` for cleaning with: + - `collections.Counter` or `collections.defaultdict()` for counting + - `dict.get()` or `dict.setdefault()` for counting + - A `list-comprehension` with a `dictionary-comprehension` +- Employing regex (_the `re` module_) for cleaning: + - `re.finditer()` with `collections.counter()`, + - `re.findall()` with `collections.counter()`, + - Or `re.split()` with `collections.counter()`. +- Using `str.translate()` with `collections.Counter` and a `walrus operator` +- Combining the built-in `filter()` with `collections.Counter` + +Various parts of these strategies can also be combined or re-combined. +For example, `collections.defaultdict()`, `dict.get()`/`dict.setdefault()`, or a `dictionary-comprehension` can be swapped for `collections.Counter()`, or vice-versa in most, if not all of the solutions. +Likewise, `str.replace()` can be swapped with regex. + + +## General guidance + + +The goal of the Word Count exercise is to count the number of words used in a given phrase. + +Before an accurate count can be done, the phrase needs to be cleaned of non-word characters (_punctuation, whitespace, tabs, etc._) and lower-cased. + +This can be thought of in three parts: + +1. Remove unwanted characters from the phrase, +2. Lowercase and split the phrase into a list of words, +3. Count up the word groups in the word list. + +Because strings are immutable in Python, any cleaning action will return a new string. + + +Most idiomatic solutions use either a chain of `str.replace()`, or a regex via the `re` module to clean the phrase. +`str.srtip()` is also very useful for dropping unwanted characters. + +For efficiency, it is best to either lowercase the phrase prior to cleaning, or just before splitting. +Otherwise, you risk adding overhead as you call `str.lower()` on individual words. + +To split, `str.split()` or `findall()`/`finditer()`/`split()` from the `re` module are usually the best strategies. +However, it is entirely possible to complete this exercise without splitting the phrase into a word list. + +Counting words most often employs the `Counter()` from `collections`, although `collections.defaultdict()`, `dict.get()` , `dict.setdefault()`, or a `dictionary comprehension` work just as well. + + +The temptation here is to go straight to regex, but `str.replace()` and `str.strip()` are surprisingly performant, and also easier to read for those unfamiliar with regex. +A complex regular expression that involves backtracking can also be much slower than `str.replace()` or `str.translate()`, so regexs should be composed and tested carefully. + + + +## Approach: String Iteration with `dict.get()` or `dict.setdefault()` + + + +```python +def count_words(sentence): + sentence = sentence.lower() + '\n' #lowercase the sentence and add a carriage return to it. + word_list = {} + new_word = '' + + for pos, value in enumerate(sentence): #enumerate() hands back both index and value + if value.isalpha() or value.isdigit(): + new_word += value + elif new_word and value == "'" and sentence[pos + 1].isalpha(): + new_word += value + else: + if new_word: + word_list[new_word] = word_list.get(new_word, 0) + 1 + new_word = '' + + return word_list +``` + + +This approach avoids splitting the phrase into a word list by iterating over each _character_ in the sentence to determine if it belongs in a valid word (_only letters and numbers are allowed_). +As each valid word is built up, it is added to the dictionary. + +Using `word_list.get()` allows for setting newly added words to value 1 while incrementing values for words already added to the dictionary. +Once added to the dictionary, the variable `new_word` is reset to empty, ready for the next word. + +For more details, see the [String iteration with Dictionary Methods][approach-string-iteration-with-dict] approach. + + +## Approach: `str.replace()` and `dict.get()` or `dict.setdefault()` + + + +```python +IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' + +def count_words(phrase): + words = (phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split()) #Returns a list, ready for further processing. + + counts = {} + + for word in words: + word = word.strip(IGNORE) + if word: + # counts[word] = counts.setdefault(word, 0) + 1 can be used here instead. + # https://stackoverflow.com/questions/7423428/python-dict-get-vs-setdefault + counts[word] = counts.get(word, 0) + 1 + + return counts + +``` + +This approach replaces unwanted characters and lower-cases the phrase before splitting it into a word list. +It then loops through the word list and uses `str.strip()` to remove characters from the IGNORE string. +If there is a word left after the `str.strip()`operation, it is added to the _counts_ dictionary. + +For more information, read the [`str.replace()` with Dictionary Methods][approach-str-replace-with-dict] approach. + + +## Approach: `str.replace()` and `comprehensions` + + + +```python +IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' + +def count_words(phrase): + cleaned = (phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split()) #Returns a list + + words = [word.strip(IGNORE) for word in cleaned] #Reprocesses cleaned, dropping unwaned characters. + + return {word : words.count(word) for word in words} + + + ###Alternatively, lines 4 and 9 can be combined### + + def count_words(phrase): + cleaned = [word.strip(IGNORE) for word in + phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split() if word] + + return {word : cleaned.count(word) for word in cleaned} +``` + + +This approach replaces the `for` loop in the previous approach with a `list comprehension`. +The `dictionary comprehension` then processes the words list, calling word.count(word) for each word (key) in the words list. + + +~~~exercism/note + +A `generator expression` cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. +Generator expressions are not indexable, and can only be iterated through once. +~~~~ + + +For more information, read the [`str.replace()` with Comprehensions][approach-str-replace-with-comprehensions] approach. + + +## Approach: `str.replace()` and `collections` + + + +```python +from string import punctuation, whitespace +from collections import Counter + +IGNORE = punctuation + whitespace + +def count_words(phrase): + words = (word.strip(IGNORE) for word in + phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split() if word) + + return Counter(words) +``` + + +This approach uses a `generator expression` to lower-case, clean, strip, and split the input phrase into words. +The words generator is then consumed by `collections.Counter()`, which counts up the words. +For convenience, `string.punctuation` `string.whitespace` are imported to replace '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'. + + +Alternatively, `collections.defaultdict()` can be used in place of `Counter()`, but requires that the generator be iterated through in an explicit loop: + + +```python +from string import punctuation, whitespace +from collections import defaultdict + +IGNORE = punctuation + whitespace + +def count_words(phrase): + words = (word.strip(IGNORE) for word in + phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split() if word) + + counts = defaultdict(int) + + for word in words: + counts[word] +=1 + + return counts +``` + +For details on these two approaches, see the [`str.replace()` with collections][approach-str-replace-with-collections] approach. + + +## Approach: Using the `re` module + + + +```python +import re +from collections import Counter +from string import punctuation + + +def count_words(phrase): + conditions = re.compile(r"[^_\s,:]+") + return Counter((match.group().strip(punctuation) for match in + re.finditer(conditions, phrase.lower()))) +``` + + +```python +import re +from collections import Counter + + +def count_words(phrase): + conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") + return Counter(conditions.findall(phrase.lower())) +``` + + + +```python +import re +from collections import Counter + + +def count_words(sentence): + conditions = re.compile(r"[\s_,\"]+") + words = (re.sub(r'\A\W+', '', re.sub(r'\W+\Z', '', word)) + for word in conditions.split(sentence.lower()) if word) + + return Counter(words) +``` + + +Regular Expressions have an almost endless variety. +This approach shows several different regular expression in combination with several different `re` module methods. + +1. `re.finditer()` to return a lazy iterator that is then fed to `collections.Counter()`. +2. `re.findall()`to return a list that is fed to `collections.Counter()` +3. `re.sub()` and `re.split()`to return a generator that is fed to `collections.Counter()`. + +For all the details on these variations, take a look at the [Using the `re` Module][approach-using-the-re-module] approach. + + +## Approach: `str.translate()` with `collections.Counter()` + + + +```python +from collections import Counter + +def count_words(phrase): + cleaner = phrase.maketrans({key: ' ' for key in ".,:-_!@$%^&"}) + cleaned = phrase.translate(cleaner).lower().split() + results = Counter((stripped for word in cleaned if + (stripped := word.strip("\"'")))) + + return results +``` + + +This approach uses (the somewhat unusual) `str.translate()` to filter out unwanted characters. +`collections.Counter` is then used to count the words. + + +The generator expression uses an assignment operator (_othewise know as the "walrus" operator `:=`_) to ensure that empty strings are excluded from the count. + +For more details, see the [Using `str.translate()` with `collections.counter()`][approach-str-translate-with-counter] approach. + + + +## Approach `filter()` with `collections.Counter()` + + + +```python +from collections import Counter +import string + +def count_words(sentence): + words = filter(None, (word.strip(string.punctuation) + for word in sentence + .lower() + .replace("_"," ") + .replace(",", " ") + .split()) + ) + return Counter(words) +``` + +This approach uses the built-in `filter()` to clean the phrase and `collections.Counter()` to count the words. +Filter is fed the same general generator expression that uses `str.replace()`, `str.lower()`, and `str.split()` seen in other approaches. + + +For more information, read the [Filter with `collections.Counter()`][approach-filter-with-counter] approach. + + +## Which approach to use? + + +The most performant of these approaches is __ for longer text, and __ for smaller text. Memory-wise, ___ has the lease overhead. + +Overall, using `str.replace()` with a `collections.Counter()` or `dict` might be the most readable to those unfamiliar with regex, and iterating through the string might be more readable to those not familiar with Python. + +To compare the performance and other tradeoffs of the approaches, take a look at the [Performance article][article-performance]. + +[approach-filter-with-counter]: https://exercism.org/tracks/python/exercises/word-count/approaches/filter-with-counter +[approach-str-replace-with-collections]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-collections +[approach-str-replace-with-comprehensions]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-comprehensions +[approach-str-replace-with-dict]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-dict +[approach-str-translate-with-counter]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-translate-with-counter +[approach-string-iteration-with-dict]: https://exercism.org/tracks/python/exercises/word-count/approaches/string-iteration-with-dict +[approach-using-the-re-module]: https://exercism.org/tracks/python/exercises/word-count/approaches/using-the-re-module +[article-performance]:https://exercism.org/tracks/python/exercises/word-count/articles/performance diff --git a/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md b/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md new file mode 100644 index 0000000000..87bf0f0005 --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md @@ -0,0 +1,23 @@ +# String Iteration with Dictionary + + + +```python +def count_words(sentence): + sentence = sentence.lower() + '\n' #lowercase the sentence and add a carriage return to it. + word_list = {} + new_word = '' + + for pos, value in enumerate(sentence): #enumerate() hands back both index and value + if value.isalpha() or value.isdigit(): + new_word += value + elif new_word and value == "'" and sentence[pos + 1].isalpha(): + new_word += value + else: + if new_word: + word_list[new_word] = word_list.get(new_word, 0) + 1 + new_word = '' + + return word_list +``` + diff --git a/exercises/practice/word-count/.approaches/str-iteration-with-dict/snippet.txt b/exercises/practice/word-count/.approaches/str-iteration-with-dict/snippet.txt new file mode 100644 index 0000000000..1e50deb4ab --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-iteration-with-dict/snippet.txt @@ -0,0 +1,8 @@ +for pos, value in enumerate(sentence): + if value.isalpha() or value.isdigit(): + new_word += value + elif new_word and value == "'" and sentence[pos + 1].isalpha(): + new_word += value + else: + if new_word: + word_list[new_word] = word_list.get(new_word, 0) + 1; new_word = '' \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md b/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md new file mode 100644 index 0000000000..058f11adb0 --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md @@ -0,0 +1,50 @@ +# String Replace with Collections + + +```python +from string import punctuation, whitespace +from collections import Counter + +IGNORE = punctuation + whitespace + +def count_words(phrase): + words = (word.strip(IGNORE) for word in + phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split() if word) + + return Counter(words) +``` + +This approach uses a `generator expression` to lowercase, clean, strip, and split the input phrase into words. + +Words is then consumed by the `Counter()` from the collections module, which counts up the words. + +For convenience, `string.punctuation` `string.whitespace` are imported to replace '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'. + + + +Alternatively, `collections.defaultdict()` can be used, but requires that the words generator be iterated through in an explicit loop: + +```python +from string import punctuation, whitespace +from collections import defaultdict + +IGNORE = punctuation + whitespace + +def count_words(phrase): + words = (word.strip(IGNORE) for word in + phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split() if word) + + counts = defaultdict(int) + + for word in words: + counts[word] +=1 + + return counts +``` + diff --git a/exercises/practice/word-count/.approaches/str-replace-with-collections/snippet.txt b/exercises/practice/word-count/.approaches/str-replace-with-collections/snippet.txt new file mode 100644 index 0000000000..1bef2f45ea --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-replace-with-collections/snippet.txt @@ -0,0 +1,8 @@ +IGNORE = punctuation + whitespace +words = (word.strip(IGNORE) for word in + phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split() if word) + +return Counter(words) \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md new file mode 100644 index 0000000000..60027d376e --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md @@ -0,0 +1,36 @@ +# String Replace with Comprehensions + + + +```python +IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' + +def count_words(phrase): + cleaned = (phrase.replace(',', ' ') + .replace('_', ' ') + .lower().split()) #Returns a list + + words = [word.strip(IGNORE) for word in cleaned] #Reprocesses cleaned, dropping unwaned characters. + + return {word : words.count(word) for word in words} + + + ###Alternatively, lines 4 and 9 can be combined### + + def count_words(phrase): + cleaned = [word.strip(IGNORE) for word in + phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split() if word] + + return {word : cleaned.count(word) for word in cleaned} +``` + + + +This approach replaces the `for` loop in the previous approach with a `list comprehension`. + +The `dictionary comprehension` then processes the words list, calling word.count(word) for each word (key) in the words list. + +Note that a `generator expression` cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/snippet.txt b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/snippet.txt new file mode 100644 index 0000000000..71430c680f --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/snippet.txt @@ -0,0 +1,8 @@ +IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' + +def count_words(phrase): + cleaned = (phrase.replace(',', ' ') + .replace('_', ' ') + .lower().split()) + words = [word.strip(IGNORE) for word in cleaned] + return {word : words.count(word) for word in words} \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md new file mode 100644 index 0000000000..2fe90f5688 --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md @@ -0,0 +1,31 @@ +# String Replace with Dictionary + + +```python +IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' + +def count_words(phrase): + words = (phrase.replace(',', ' ') + .replace('_', ' ') + .lower() + .split()) #Returns a list, ready for further processing. + + counts = {} + + for word in words: + word = word.strip(IGNORE) + if word: + # counts[word] = counts.setdefault(word, 0) + 1 can be used here instead. + # https://stackoverflow.com/questions/7423428/python-dict-get-vs-setdefault + counts[word] = counts.get(word, 0) + 1 + + return counts +``` + + + +This approach replaces unwanted characters and lowercases the phrase before splitting it into a word list. + +It then loops through the word list and uses `str.strip()` to remove characters from the IGNORE string. + +If there is a word left after the `str.strip()`operation, it is added to the _counts_ dictionary. \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/str-replace-with-dict/snippet.txt b/exercises/practice/word-count/.approaches/str-replace-with-dict/snippet.txt new file mode 100644 index 0000000000..269b632221 --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-replace-with-dict/snippet.txt @@ -0,0 +1,8 @@ +counts = {} + +for word in words: + word = word.strip(IGNORE) + if word: + counts[word] = counts.get(word, 0) + 1 + +return counts \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md b/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md new file mode 100644 index 0000000000..276f1d2c8a --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md @@ -0,0 +1,23 @@ +# String Translate with Counter + + + +```python +from collections import Counter + +def count_words(phrase): + cleaner = phrase.maketrans({key: ' ' for key in ".,:-_!@$%^&"}) + cleaned = phrase.translate(cleaner).lower().split() + results = Counter((stripped for word in cleaned if + (stripped := word.strip("\"'")))) + + return results +``` + + + +This approach (somewhat unusually) uses `str.translate()` to filter out unwanted characters. + +`collections.Counter` is then used to count the words. + +The generator expression uses an assignment operator (_othewise know as the "walrus" operator `:=`_) to ensure that empty strings are excluded from the count. \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/str-translate-with-counter/snippet.txt b/exercises/practice/word-count/.approaches/str-translate-with-counter/snippet.txt new file mode 100644 index 0000000000..35965c2206 --- /dev/null +++ b/exercises/practice/word-count/.approaches/str-translate-with-counter/snippet.txt @@ -0,0 +1,7 @@ +def count_words(phrase): + cleaner = phrase.maketrans({key: ' ' for key in ".,:-_!@$%^&"}) + cleaned = phrase.translate(cleaner).lower().split() + results = Counter((stripped for word in cleaned if + (stripped := word.strip("\"'")))) + + return results \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/using-the-re-module/content.md b/exercises/practice/word-count/.approaches/using-the-re-module/content.md new file mode 100644 index 0000000000..ad56f0323a --- /dev/null +++ b/exercises/practice/word-count/.approaches/using-the-re-module/content.md @@ -0,0 +1,57 @@ +# Using the Re Module + + + +```python +import re +from collections import Counter +from string import punctuation + + +def count_words(phrase): + conditions = re.compile(r"[^_\s,:]+") + return Counter((match.group().strip(punctuation) for match in + re.finditer(conditions, phrase.lower()))) +``` + + + + +```python +import re +from collections import Counter + + +def count_words(phrase): + conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") + return Counter(conditions.findall(phrase.lower())) +``` + + + + + +```python +import re +from collections import Counter + + +def count_words(sentence): + conditions = re.compile(r"[\s_,\"]+") + words = (re.sub(r'\A\W+', '', re.sub(r'\W+\Z', '', word)) + for word in conditions.split(sentence.lower()) if word) + + return Counter(words) +``` + + + +There are many variations that can be used in a regular expressions. + +This approach shows several different regexs, in combination with several different `re` methods. + +The first variation uses `re.findite()` to return a lazy iterator that is then fed to `collections.Counter`. + +The second variation uses `re.findall()`to return a list that is fed to `collections.Counter` + +The final variation uses `re.sub()` and `re.split()`to return a generator that is fed to `collections.Counter`. \ No newline at end of file diff --git a/exercises/practice/word-count/.approaches/using-the-re-module/snippet.txt b/exercises/practice/word-count/.approaches/using-the-re-module/snippet.txt new file mode 100644 index 0000000000..623a3b78e0 --- /dev/null +++ b/exercises/practice/word-count/.approaches/using-the-re-module/snippet.txt @@ -0,0 +1,7 @@ +import re +from collections import Counter + + +def count_words(phrase): + conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") + return Counter(conditions.findall(phrase.lower())) \ No newline at end of file diff --git a/exercises/practice/word-count/.articles/config.json b/exercises/practice/word-count/.articles/config.json new file mode 100644 index 0000000000..0b87f8bfd8 --- /dev/null +++ b/exercises/practice/word-count/.articles/config.json @@ -0,0 +1,11 @@ +{ + "articles": [ + { + "uuid": "c8434a98-716f-48d8-ba34-bb1d159fb420", + "slug": "performance", + "title": "Performance deep dive", + "blurb": "Deep dive to find out the most performant approach for counting words.", + "authors": ["bethanyg"] + } + ] +} \ No newline at end of file diff --git a/exercises/practice/word-count/.articles/performance/code/Benchmark.py b/exercises/practice/word-count/.articles/performance/code/Benchmark.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/exercises/practice/word-count/.articles/performance/content.md b/exercises/practice/word-count/.articles/performance/content.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/exercises/practice/word-count/.articles/performance/snippet.md b/exercises/practice/word-count/.articles/performance/snippet.md new file mode 100644 index 0000000000..e69de29bb2 From 60e0767d2a03a7264bc52310059dba2ade7246d0 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:27:42 -0500 Subject: [PATCH 2/9] formatting, spelling, and grammar fixes --- .../word-count/.approaches/config.json | 6 +- .../filter-with-counter/content.md | 18 +- .../filter-with-counter/snippet.txt | 12 +- .../word-count/.approaches/introduction.md | 175 +++++++----------- .../str-iteration-with-dict/content.md | 16 +- .../str-iteration-with-dict/snippet.txt | 6 +- .../str-replace-with-collections/content.md | 20 +- .../str-replace-with-collections/snippet.txt | 12 +- .../content.md | 24 +-- .../snippet.txt | 2 +- .../str-replace-with-dict/content.md | 11 +- .../str-replace-with-dict/snippet.txt | 2 +- .../str-translate-with-counter/content.md | 10 +- .../using-the-re-module/content.md | 44 ++--- .../using-the-re-module/snippet.txt | 4 +- 15 files changed, 148 insertions(+), 214 deletions(-) diff --git a/exercises/practice/word-count/.approaches/config.json b/exercises/practice/word-count/.approaches/config.json index 9c72ccbccd..9682410535 100644 --- a/exercises/practice/word-count/.approaches/config.json +++ b/exercises/practice/word-count/.approaches/config.json @@ -34,8 +34,8 @@ { "uuid": "2afed504-500d-4415-a507-b78311bde777", "slug": "using-the-re-module", - "title": "Using the Re Module", - "blurb": "Python's Re module is both versatile and powerful.", + "title": "Using the re Module", + "blurb": "Python's re module is both versatile and powerful.", "authors": ["bethanyg"] }, { @@ -53,4 +53,4 @@ "authors": ["bethanyg"] } ] -} \ No newline at end of file +} diff --git a/exercises/practice/word-count/.approaches/filter-with-counter/content.md b/exercises/practice/word-count/.approaches/filter-with-counter/content.md index 3ff0b8ce8a..06e56fb77c 100644 --- a/exercises/practice/word-count/.approaches/filter-with-counter/content.md +++ b/exercises/practice/word-count/.approaches/filter-with-counter/content.md @@ -1,19 +1,17 @@ # Filter with Counter - ```python from collections import Counter import string def count_words(sentence): - words = filter(None, (word.strip(string.punctuation) - for word in sentence - .lower() - .replace("_"," ") - .replace(",", " ") - .split()) - ) + words = filter(None, ( + word.strip(string.punctuation) + for word in sentence + .lower() + .replace("_"," ") + .replace(",", " ") + .split() + )) return Counter(words) ``` - - diff --git a/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt b/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt index db209ab074..2c6d303db3 100644 --- a/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt +++ b/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt @@ -1,8 +1,6 @@ def count_words(sentence): - words = filter(None, (word.strip(string.punctuation) - for word in sentence.lower() - .replace("_"," ") - .replace(",", " ") - .split())) - - return Counter(words) \ No newline at end of file + words = filter(None, ( + word.strip(string.punctuation) + for word in sentence.lower().replace("_"," ").replace(",", " ").split() + )) + return Counter(words) diff --git a/exercises/practice/word-count/.approaches/introduction.md b/exercises/practice/word-count/.approaches/introduction.md index 53624ae6e6..26deafdea8 100644 --- a/exercises/practice/word-count/.approaches/introduction.md +++ b/exercises/practice/word-count/.approaches/introduction.md @@ -5,13 +5,13 @@ Among them are: - String iteration with `dict.get()` - Using `str.replace()` for cleaning with: - - `collections.Counter` or `collections.defaultdict()` for counting - - `dict.get()` or `dict.setdefault()` for counting + - `collections.Counter` or `collections.defaultdict()` for counting + - `dict.get()` or `dict.setdefault()` for counting - A `list-comprehension` with a `dictionary-comprehension` -- Employing regex (_the `re` module_) for cleaning: - - `re.finditer()` with `collections.counter()`, - - `re.findall()` with `collections.counter()`, - - Or `re.split()` with `collections.counter()`. +- Employing regex (_the `re` module_) for cleaning: + - `re.finditer()` with `collections.counter()` + - `re.findall()` with `collections.counter()` + - `re.split()` with `collections.counter()` - Using `str.translate()` with `collections.Counter` and a `walrus operator` - Combining the built-in `filter()` with `collections.Counter` @@ -22,21 +22,20 @@ Likewise, `str.replace()` can be swapped with regex. ## General guidance - The goal of the Word Count exercise is to count the number of words used in a given phrase. Before an accurate count can be done, the phrase needs to be cleaned of non-word characters (_punctuation, whitespace, tabs, etc._) and lower-cased. This can be thought of in three parts: -1. Remove unwanted characters from the phrase, -2. Lowercase and split the phrase into a list of words, -3. Count up the word groups in the word list. +1. Remove unwanted characters from the phrase, +2. Lowercase and split the phrase into a list of words, +3. Count up the word groups in the word list. Because strings are immutable in Python, any cleaning action will return a new string. -Most idiomatic solutions use either a chain of `str.replace()`, or a regex via the `re` module to clean the phrase. +Most idiomatic solutions use either a chain of `str.replace()`, or a regex via the `re` module to clean the phrase. `str.srtip()` is also very useful for dropping unwanted characters. For efficiency, it is best to either lowercase the phrase prior to cleaning, or just before splitting. @@ -52,32 +51,27 @@ The temptation here is to go straight to regex, but `str.replace()` and `str.str A complex regular expression that involves backtracking can also be much slower than `str.replace()` or `str.translate()`, so regexs should be composed and tested carefully. - ## Approach: String Iteration with `dict.get()` or `dict.setdefault()` - - ```python def count_words(sentence): - sentence = sentence.lower() + '\n' #lowercase the sentence and add a carriage return to it. + sentence = sentence.lower() + '\n' # Lowercase the sentence and add a carriage return to it. word_list = {} new_word = '' - - for pos, value in enumerate(sentence): #enumerate() hands back both index and value + + for pos, value in enumerate(sentence): # enumerate() hands back both index and value if value.isalpha() or value.isdigit(): new_word += value elif new_word and value == "'" and sentence[pos + 1].isalpha(): new_word += value - else: - if new_word: - word_list[new_word] = word_list.get(new_word, 0) + 1 + elif new_word: + word_list[new_word] = word_list.get(new_word, 0) + 1 new_word = '' - + return word_list ``` - -This approach avoids splitting the phrase into a word list by iterating over each _character_ in the sentence to determine if it belongs in a valid word (_only letters and numbers are allowed_). +This approach avoids splitting the phrase into a word list by iterating over each _character_ in the sentence to determine if it belongs in a valid word (_only letters and numbers are allowed_). As each valid word is built up, it is added to the dictionary. Using `word_list.get()` allows for setting newly added words to value 1 while incrementing values for words already added to the dictionary. @@ -86,9 +80,7 @@ Once added to the dictionary, the variable `new_word` is reset to empty, ready f For more details, see the [String iteration with Dictionary Methods][approach-string-iteration-with-dict] approach. -## Approach: `str.replace()` and `dict.get()` or `dict.setdefault()` - - +## Approach: `str.replace()` and `dict.get()` or `dict.setdefault()` ```python IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' @@ -97,7 +89,7 @@ def count_words(phrase): words = (phrase.replace(',', ' ') .replace('_', ' ') .lower() - .split()) #Returns a list, ready for further processing. + .split()) # Returns a list, ready for further processing. counts = {} @@ -106,23 +98,20 @@ def count_words(phrase): if word: # counts[word] = counts.setdefault(word, 0) + 1 can be used here instead. # https://stackoverflow.com/questions/7423428/python-dict-get-vs-setdefault - counts[word] = counts.get(word, 0) + 1 + counts[word] = counts.get(word, 0) + 1 return counts - ``` This approach replaces unwanted characters and lower-cases the phrase before splitting it into a word list. It then loops through the word list and uses `str.strip()` to remove characters from the IGNORE string. If there is a word left after the `str.strip()`operation, it is added to the _counts_ dictionary. -For more information, read the [`str.replace()` with Dictionary Methods][approach-str-replace-with-dict] approach. +For more information, read the [`str.replace()` with Dictionary][approach-str-replace-with-dict] approach. ## Approach: `str.replace()` and `comprehensions` - - ```python IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' @@ -130,17 +119,16 @@ def count_words(phrase): cleaned = (phrase.replace(',', ' ') .replace('_', ' ') .lower() - .split()) #Returns a list - - words = [word.strip(IGNORE) for word in cleaned] #Reprocesses cleaned, dropping unwaned characters. + .split()) # Returns a list + + words = [word.strip(IGNORE) for word in cleaned] # Reprocesses cleaned, dropping unwaned characters. return {word : words.count(word) for word in words} - - - ###Alternatively, lines 4 and 9 can be combined### - - def count_words(phrase): - cleaned = [word.strip(IGNORE) for word in + +### Alternatively, lines 4 and 9 can be combined ### + +def count_words(phrase): + cleaned = [word.strip(IGNORE) for word in phrase.replace(',', ' ') .replace('_', ' ') .lower() @@ -149,13 +137,11 @@ def count_words(phrase): return {word : cleaned.count(word) for word in cleaned} ``` - This approach replaces the `for` loop in the previous approach with a `list comprehension`. -The `dictionary comprehension` then processes the words list, calling word.count(word) for each word (key) in the words list. - +The `dictionary comprehension` then processes the words list, calling `.count(word)` for each word (key) in the words list. -~~~exercism/note +~~~~exercism/note A `generator expression` cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. Generator expressions are not indexable, and can only be iterated through once. ~~~~ @@ -166,8 +152,6 @@ For more information, read the [`str.replace()` with Comprehensions][approach-st ## Approach: `str.replace()` and `collections` - - ```python from string import punctuation, whitespace from collections import Counter @@ -175,7 +159,7 @@ from collections import Counter IGNORE = punctuation + whitespace def count_words(phrase): - words = (word.strip(IGNORE) for word in + words = (word.strip(IGNORE) for word in phrase.replace(',', ' ') .replace('_', ' ') .lower() @@ -184,10 +168,9 @@ def count_words(phrase): return Counter(words) ``` - This approach uses a `generator expression` to lower-case, clean, strip, and split the input phrase into words. The words generator is then consumed by `collections.Counter()`, which counts up the words. -For convenience, `string.punctuation` `string.whitespace` are imported to replace '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'. +For convenience, `string.punctuation` and `string.whitespace` are imported to replace ``'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'``. Alternatively, `collections.defaultdict()` can be used in place of `Counter()`, but requires that the generator be iterated through in an explicit loop: @@ -200,7 +183,7 @@ from collections import defaultdict IGNORE = punctuation + whitespace def count_words(phrase): - words = (word.strip(IGNORE) for word in + words = (word.strip(IGNORE) for word in phrase.replace(',', ' ') .replace('_', ' ') .lower() @@ -209,7 +192,7 @@ def count_words(phrase): counts = defaultdict(int) for word in words: - counts[word] +=1 + counts[word] += 1 return counts ``` @@ -217,62 +200,51 @@ def count_words(phrase): For details on these two approaches, see the [`str.replace()` with collections][approach-str-replace-with-collections] approach. -## Approach: Using the `re` module - - +## Approach: Using the `re` module ```python import re from collections import Counter from string import punctuation - def count_words(phrase): - conditions = re.compile(r"[^_\s,:]+") - return Counter((match.group().strip(punctuation) for match in - re.finditer(conditions, phrase.lower()))) -``` + conditions = re.compile(r"[^_\s,:]+") + return Counter(match.group().strip(punctuation) for match in + re.finditer(conditions, phrase.lower())) +### OR ### -```python import re from collections import Counter - def count_words(phrase): - conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") - return Counter(conditions.findall(phrase.lower())) -``` - + conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") + return Counter(conditions.findall(phrase.lower())) +### OR ### -```python import re from collections import Counter - def count_words(sentence): - conditions = re.compile(r"[\s_,\"]+") - words = (re.sub(r'\A\W+', '', re.sub(r'\W+\Z', '', word)) - for word in conditions.split(sentence.lower()) if word) - - return Counter(words) -``` + conditions = re.compile(r"[\s_,\"]+") + words = (re.sub(r'\A\W+', '', re.sub(r'\W+\Z', '', word)) + for word in conditions.split(sentence.lower()) if word) + return Counter(words) +``` Regular Expressions have an almost endless variety. This approach shows several different regular expression in combination with several different `re` module methods. -1. `re.finditer()` to return a lazy iterator that is then fed to `collections.Counter()`. -2. `re.findall()`to return a list that is fed to `collections.Counter()` -3. `re.sub()` and `re.split()`to return a generator that is fed to `collections.Counter()`. +1. `re.finditer()` to return a lazy iterator that is then fed to `collections.Counter()`. +2. `re.findall()` to return a list that is fed to `collections.Counter()` +3. `re.sub()` and `re.split()`to return a generator that is fed to `collections.Counter()`. For all the details on these variations, take a look at the [Using the `re` Module][approach-using-the-re-module] approach. -## Approach: `str.translate()` with `collections.Counter()` - - +## Approach: `str.translate()` with `collections.Counter()` ```python from collections import Counter @@ -280,14 +252,13 @@ from collections import Counter def count_words(phrase): cleaner = phrase.maketrans({key: ' ' for key in ".,:-_!@$%^&"}) cleaned = phrase.translate(cleaner).lower().split() - results = Counter((stripped for word in cleaned if - (stripped := word.strip("\"'")))) + results = Counter(stripped for word in cleaned + if (stripped := word.strip("\"'"))) return results ``` - -This approach uses (the somewhat unusual) `str.translate()` to filter out unwanted characters. +This approach uses the (somewhat unusual) `str.translate()` to filter out unwanted characters. `collections.Counter` is then used to count the words. @@ -296,23 +267,21 @@ The generator expression uses an assignment operator (_othewise know as the "wal For more details, see the [Using `str.translate()` with `collections.counter()`][approach-str-translate-with-counter] approach. - ## Approach `filter()` with `collections.Counter()` - - ```python from collections import Counter import string def count_words(sentence): - words = filter(None, (word.strip(string.punctuation) - for word in sentence - .lower() - .replace("_"," ") - .replace(",", " ") - .split()) - ) + words = filter(None, ( + word.strip(string.punctuation) + for word in sentence + .lower() + .replace("_"," ") + .replace(",", " ") + .split() + )) return Counter(words) ``` @@ -325,18 +294,18 @@ For more information, read the [Filter with `collections.Counter()`][approach-fi ## Which approach to use? - -The most performant of these approaches is __ for longer text, and __ for smaller text. Memory-wise, ___ has the lease overhead. +The most performant of these approaches is __ for longer text, and __ for smaller text. Memory-wise, ___ has the least overhead. Overall, using `str.replace()` with a `collections.Counter()` or `dict` might be the most readable to those unfamiliar with regex, and iterating through the string might be more readable to those not familiar with Python. To compare the performance and other tradeoffs of the approaches, take a look at the [Performance article][article-performance]. -[approach-filter-with-counter]: https://exercism.org/tracks/python/exercises/word-count/approaches/filter-with-counter -[approach-str-replace-with-collections]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-collections -[approach-str-replace-with-comprehensions]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-comprehensions -[approach-str-replace-with-dict]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-dict -[approach-str-translate-with-counter]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-translate-with-counter -[approach-string-iteration-with-dict]: https://exercism.org/tracks/python/exercises/word-count/approaches/string-iteration-with-dict -[approach-using-the-re-module]: https://exercism.org/tracks/python/exercises/word-count/approaches/using-the-re-module + +[approach-filter-with-counter]: https://exercism.org/tracks/python/exercises/word-count/approaches/filter-with-counter +[approach-str-replace-with-collections]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-collections +[approach-str-replace-with-comprehensions]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-comprehensions +[approach-str-replace-with-dict]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-replace-with-dict +[approach-str-translate-with-counter]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-translate-with-counter +[approach-string-iteration-with-dict]: https://exercism.org/tracks/python/exercises/word-count/approaches/string-iteration-with-dict +[approach-using-the-re-module]: https://exercism.org/tracks/python/exercises/word-count/approaches/using-the-re-module [article-performance]:https://exercism.org/tracks/python/exercises/word-count/articles/performance diff --git a/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md b/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md index 87bf0f0005..6a372289be 100644 --- a/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md +++ b/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md @@ -1,23 +1,19 @@ # String Iteration with Dictionary - - ```python def count_words(sentence): - sentence = sentence.lower() + '\n' #lowercase the sentence and add a carriage return to it. + sentence = sentence.lower() + '\n' # Lowercase the sentence and add a carriage return to it. word_list = {} new_word = '' - - for pos, value in enumerate(sentence): #enumerate() hands back both index and value + + for pos, value in enumerate(sentence): # enumerate() hands back both index and value if value.isalpha() or value.isdigit(): new_word += value elif new_word and value == "'" and sentence[pos + 1].isalpha(): new_word += value - else: - if new_word: - word_list[new_word] = word_list.get(new_word, 0) + 1 + elif new_word: + word_list[new_word] = word_list.get(new_word, 0) + 1 new_word = '' - + return word_list ``` - diff --git a/exercises/practice/word-count/.approaches/str-iteration-with-dict/snippet.txt b/exercises/practice/word-count/.approaches/str-iteration-with-dict/snippet.txt index 1e50deb4ab..fba55ec518 100644 --- a/exercises/practice/word-count/.approaches/str-iteration-with-dict/snippet.txt +++ b/exercises/practice/word-count/.approaches/str-iteration-with-dict/snippet.txt @@ -3,6 +3,6 @@ for pos, value in enumerate(sentence): new_word += value elif new_word and value == "'" and sentence[pos + 1].isalpha(): new_word += value - else: - if new_word: - word_list[new_word] = word_list.get(new_word, 0) + 1; new_word = '' \ No newline at end of file + elif new_word: + word_list[new_word] = word_list.get(new_word, 0) + 1 + new_word = '' diff --git a/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md b/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md index 058f11adb0..7dd2614d6b 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md @@ -1,6 +1,5 @@ # String Replace with Collections - ```python from string import punctuation, whitespace from collections import Counter @@ -8,12 +7,13 @@ from collections import Counter IGNORE = punctuation + whitespace def count_words(phrase): - words = (word.strip(IGNORE) for word in - phrase.replace(',', ' ') + words = (word.strip(IGNORE) + for word in phrase + .replace(',', ' ') .replace('_', ' ') - .lower() - .split() if word) - + .lower().split() + if word) + return Counter(words) ``` @@ -21,11 +21,10 @@ This approach uses a `generator expression` to lowercase, clean, strip, and spli Words is then consumed by the `Counter()` from the collections module, which counts up the words. -For convenience, `string.punctuation` `string.whitespace` are imported to replace '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'. - +For convenience, `string.punctuation` and `string.whitespace` are imported to replace ``'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'``. -Alternatively, `collections.defaultdict()` can be used, but requires that the words generator be iterated through in an explicit loop: +Alternatively, `collections.defaultdict()` can be used, but requires that the words generator be iterated through in an explicit loop: ```python from string import punctuation, whitespace @@ -34,7 +33,7 @@ from collections import defaultdict IGNORE = punctuation + whitespace def count_words(phrase): - words = (word.strip(IGNORE) for word in + words = (word.strip(IGNORE) for word in phrase.replace(',', ' ') .replace('_', ' ') .lower() @@ -47,4 +46,3 @@ def count_words(phrase): return counts ``` - diff --git a/exercises/practice/word-count/.approaches/str-replace-with-collections/snippet.txt b/exercises/practice/word-count/.approaches/str-replace-with-collections/snippet.txt index 1bef2f45ea..9b2e0e53ad 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-collections/snippet.txt +++ b/exercises/practice/word-count/.approaches/str-replace-with-collections/snippet.txt @@ -1,8 +1,8 @@ IGNORE = punctuation + whitespace -words = (word.strip(IGNORE) for word in - phrase.replace(',', ' ') +words = (word.strip(IGNORE) + for word in phrase + .replace(',', ' ') .replace('_', ' ') - .lower() - .split() if word) - -return Counter(words) \ No newline at end of file + .lower().split() + if word) +return Counter(words) diff --git a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md index 60027d376e..c9873db3c4 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md @@ -1,24 +1,22 @@ # String Replace with Comprehensions - - ```python IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' def count_words(phrase): cleaned = (phrase.replace(',', ' ') .replace('_', ' ') - .lower().split()) #Returns a list - - words = [word.strip(IGNORE) for word in cleaned] #Reprocesses cleaned, dropping unwaned characters. + .lower() + .split()) # Returns a list + + words = [word.strip(IGNORE) for word in cleaned] # Reprocesses cleaned, dropping unwaned characters. return {word : words.count(word) for word in words} - - - ###Alternatively, lines 4 and 9 can be combined### - - def count_words(phrase): - cleaned = [word.strip(IGNORE) for word in + +### Alternatively, lines 4 and 9 can be combined ### + +def count_words(phrase): + cleaned = [word.strip(IGNORE) for word in phrase.replace(',', ' ') .replace('_', ' ') .lower() @@ -27,10 +25,8 @@ def count_words(phrase): return {word : cleaned.count(word) for word in cleaned} ``` - - This approach replaces the `for` loop in the previous approach with a `list comprehension`. The `dictionary comprehension` then processes the words list, calling word.count(word) for each word (key) in the words list. -Note that a `generator expression` cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. \ No newline at end of file +Note that a `generator expression` cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. diff --git a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/snippet.txt b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/snippet.txt index 71430c680f..1fd8a53fe2 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/snippet.txt +++ b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/snippet.txt @@ -5,4 +5,4 @@ def count_words(phrase): .replace('_', ' ') .lower().split()) words = [word.strip(IGNORE) for word in cleaned] - return {word : words.count(word) for word in words} \ No newline at end of file + return {word : words.count(word) for word in words} diff --git a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md index 2fe90f5688..e347f6ff77 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md @@ -1,6 +1,5 @@ # String Replace with Dictionary - ```python IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' @@ -8,7 +7,7 @@ def count_words(phrase): words = (phrase.replace(',', ' ') .replace('_', ' ') .lower() - .split()) #Returns a list, ready for further processing. + .split()) # Returns a list, ready for further processing. counts = {} @@ -17,15 +16,13 @@ def count_words(phrase): if word: # counts[word] = counts.setdefault(word, 0) + 1 can be used here instead. # https://stackoverflow.com/questions/7423428/python-dict-get-vs-setdefault - counts[word] = counts.get(word, 0) + 1 + counts[word] = counts.get(word, 0) + 1 return counts ``` - - This approach replaces unwanted characters and lowercases the phrase before splitting it into a word list. -It then loops through the word list and uses `str.strip()` to remove characters from the IGNORE string. +It then loops through the word list and uses `str.strip()` to remove characters from the `IGNORE` string. -If there is a word left after the `str.strip()`operation, it is added to the _counts_ dictionary. \ No newline at end of file +If there is a word left after the `str.strip()` operation, it is added to the _counts_ dictionary. diff --git a/exercises/practice/word-count/.approaches/str-replace-with-dict/snippet.txt b/exercises/practice/word-count/.approaches/str-replace-with-dict/snippet.txt index 269b632221..7f739af116 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-dict/snippet.txt +++ b/exercises/practice/word-count/.approaches/str-replace-with-dict/snippet.txt @@ -5,4 +5,4 @@ for word in words: if word: counts[word] = counts.get(word, 0) + 1 -return counts \ No newline at end of file +return counts diff --git a/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md b/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md index 276f1d2c8a..e0d966b326 100644 --- a/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md +++ b/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md @@ -1,23 +1,19 @@ # String Translate with Counter - - ```python from collections import Counter def count_words(phrase): cleaner = phrase.maketrans({key: ' ' for key in ".,:-_!@$%^&"}) cleaned = phrase.translate(cleaner).lower().split() - results = Counter((stripped for word in cleaned if - (stripped := word.strip("\"'")))) + results = Counter(stripped for word in cleaned + if (stripped := word.strip("\"'"))) return results ``` - - This approach (somewhat unusually) uses `str.translate()` to filter out unwanted characters. `collections.Counter` is then used to count the words. -The generator expression uses an assignment operator (_othewise know as the "walrus" operator `:=`_) to ensure that empty strings are excluded from the count. \ No newline at end of file +The generator expression uses an assignment operator (_otherwise know as the "walrus" operator `:=`_) to ensure that empty strings are excluded from the count. diff --git a/exercises/practice/word-count/.approaches/using-the-re-module/content.md b/exercises/practice/word-count/.approaches/using-the-re-module/content.md index ad56f0323a..d0d1133b0d 100644 --- a/exercises/practice/word-count/.approaches/using-the-re-module/content.md +++ b/exercises/practice/word-count/.approaches/using-the-re-module/content.md @@ -1,57 +1,43 @@ # Using the Re Module - - ```python import re from collections import Counter from string import punctuation - def count_words(phrase): - conditions = re.compile(r"[^_\s,:]+") - return Counter((match.group().strip(punctuation) for match in - re.finditer(conditions, phrase.lower()))) -``` - + conditions = re.compile(r"[^_\s,:]+") + return Counter(match.group().strip(punctuation) for match in + re.finditer(conditions, phrase.lower())) +### OR ### - -```python import re from collections import Counter - def count_words(phrase): - conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") - return Counter(conditions.findall(phrase.lower())) -``` + conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") + return Counter(conditions.findall(phrase.lower())) +### OR ### - - - -```python import re from collections import Counter - def count_words(sentence): - conditions = re.compile(r"[\s_,\"]+") - words = (re.sub(r'\A\W+', '', re.sub(r'\W+\Z', '', word)) - for word in conditions.split(sentence.lower()) if word) - - return Counter(words) -``` - + conditions = re.compile(r"[\s_,\"]+") + words = (re.sub(r'\A\W+', '', re.sub(r'\W+\Z', '', word)) + for word in conditions.split(sentence.lower()) if word) + return Counter(words) +``` There are many variations that can be used in a regular expressions. This approach shows several different regexs, in combination with several different `re` methods. -The first variation uses `re.findite()` to return a lazy iterator that is then fed to `collections.Counter`. +The first variation uses `re.finditer()` to return a lazy iterator that is then fed to `collections.Counter`. -The second variation uses `re.findall()`to return a list that is fed to `collections.Counter` +The second variation uses `re.findall()` to return a list that is fed to `collections.Counter`. -The final variation uses `re.sub()` and `re.split()`to return a generator that is fed to `collections.Counter`. \ No newline at end of file +The final variation uses `re.sub()` and `re.split()` to return a generator that is fed to `collections.Counter`. diff --git a/exercises/practice/word-count/.approaches/using-the-re-module/snippet.txt b/exercises/practice/word-count/.approaches/using-the-re-module/snippet.txt index 623a3b78e0..2a58f8a36f 100644 --- a/exercises/practice/word-count/.approaches/using-the-re-module/snippet.txt +++ b/exercises/practice/word-count/.approaches/using-the-re-module/snippet.txt @@ -3,5 +3,5 @@ from collections import Counter def count_words(phrase): - conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") - return Counter(conditions.findall(phrase.lower())) \ No newline at end of file + conditions = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") + return Counter(conditions.findall(phrase.lower())) From 8d576e7377e99038776f524b3c407b18fdc98719 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:13:15 -0500 Subject: [PATCH 3/9] more formatting/spelling fixes & add links --- .../word-count/.approaches/introduction.md | 81 ++++++++++++------- .../str-replace-with-collections/content.md | 26 ++++-- .../content.md | 12 ++- .../str-replace-with-dict/content.md | 5 +- .../str-translate-with-counter/content.md | 12 ++- .../using-the-re-module/content.md | 16 +++- 6 files changed, 104 insertions(+), 48 deletions(-) diff --git a/exercises/practice/word-count/.approaches/introduction.md b/exercises/practice/word-count/.approaches/introduction.md index 26deafdea8..ae2b05e278 100644 --- a/exercises/practice/word-count/.approaches/introduction.md +++ b/exercises/practice/word-count/.approaches/introduction.md @@ -7,16 +7,16 @@ Among them are: - Using `str.replace()` for cleaning with: - `collections.Counter` or `collections.defaultdict()` for counting - `dict.get()` or `dict.setdefault()` for counting - - A `list-comprehension` with a `dictionary-comprehension` + - A `list comprehension` with a `dictionary comprehension` - Employing regex (_the `re` module_) for cleaning: - - `re.finditer()` with `collections.counter()` - - `re.findall()` with `collections.counter()` - - `re.split()` with `collections.counter()` + - `re.finditer()` with `collections.Counter()` + - `re.findall()` with `collections.Counter()` + - `re.split()` with `collections.Counter()` - Using `str.translate()` with `collections.Counter` and a `walrus operator` - Combining the built-in `filter()` with `collections.Counter` Various parts of these strategies can also be combined or re-combined. -For example, `collections.defaultdict()`, `dict.get()`/`dict.setdefault()`, or a `dictionary-comprehension` can be swapped for `collections.Counter()`, or vice-versa in most, if not all of the solutions. +For example, `collections.defaultdict()`, `dict.get()`/`dict.setdefault()`, or a `dictionary comprehension` can be swapped for `collections.Counter()` or vice-versa in most, if not all, of the solutions. Likewise, `str.replace()` can be swapped with regex. @@ -35,20 +35,20 @@ This can be thought of in three parts: Because strings are immutable in Python, any cleaning action will return a new string. -Most idiomatic solutions use either a chain of `str.replace()`, or a regex via the `re` module to clean the phrase. -`str.srtip()` is also very useful for dropping unwanted characters. +Most idiomatic solutions use either a chain of [`str.replace()`][str-replace], or a regex via the [`re` module][re-module] to clean the phrase. +[`str.strip()`][str-strip] is also very useful for dropping unwanted characters. For efficiency, it is best to either lowercase the phrase prior to cleaning, or just before splitting. -Otherwise, you risk adding overhead as you call `str.lower()` on individual words. +Otherwise, you risk adding overhead as you call [`str.lower()`][str-lower] on individual words. -To split, `str.split()` or `findall()`/`finditer()`/`split()` from the `re` module are usually the best strategies. +To split, [`str.split()`][str-split] or [`findall()`][re-findall]/[`finditer()`][re-finditer]/[`split()`][re-split] from the `re` module are usually the best strategies. However, it is entirely possible to complete this exercise without splitting the phrase into a word list. -Counting words most often employs the `Counter()` from `collections`, although `collections.defaultdict()`, `dict.get()` , `dict.setdefault()`, or a `dictionary comprehension` work just as well. +Counting words most often employs the [`Counter()` class][collections-counter] from the [`collections` module][collections-module], although [`collections.defaultdict()`][collections-defaultdict], [`dict.get()`][dict-get], [`dict.setdefault()`][dict-setdefault], or a [dictionary comprehension][dict-comprehension] work just as well. The temptation here is to go straight to regex, but `str.replace()` and `str.strip()` are surprisingly performant, and also easier to read for those unfamiliar with regex. -A complex regular expression that involves backtracking can also be much slower than `str.replace()` or `str.translate()`, so regexs should be composed and tested carefully. +A complex regular expression that involves backtracking can also be much slower than `str.replace()` or [`str.translate()`][str-translate], so regexes should be composed and tested carefully. ## Approach: String Iteration with `dict.get()` or `dict.setdefault()` @@ -104,8 +104,8 @@ def count_words(phrase): ``` This approach replaces unwanted characters and lower-cases the phrase before splitting it into a word list. -It then loops through the word list and uses `str.strip()` to remove characters from the IGNORE string. -If there is a word left after the `str.strip()`operation, it is added to the _counts_ dictionary. +It then loops through the word list and uses [`str.strip()`][str-strip] to remove characters from the IGNORE string. +If there is a word left after the `str.strip()` operation, it is added to the _counts_ dictionary. For more information, read the [`str.replace()` with Dictionary][approach-str-replace-with-dict] approach. @@ -137,12 +137,12 @@ def count_words(phrase): return {word : cleaned.count(word) for word in cleaned} ``` -This approach replaces the `for` loop in the previous approach with a `list comprehension`. -The `dictionary comprehension` then processes the words list, calling `.count(word)` for each word (key) in the words list. +This approach replaces the `for` loop in the previous approach with a [`list comprehension`][list-comprehension]. +The [`dictionary comprehension`][dict-comprehension] then processes the words list, calling [`.count(word)`][str-count] for each word (key) in the words list. ~~~~exercism/note -A `generator expression` cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. +A [generator expression][generator-expression] cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. Generator expressions are not indexable, and can only be iterated through once. ~~~~ @@ -168,12 +168,12 @@ def count_words(phrase): return Counter(words) ``` -This approach uses a `generator expression` to lower-case, clean, strip, and split the input phrase into words. -The words generator is then consumed by `collections.Counter()`, which counts up the words. -For convenience, `string.punctuation` and `string.whitespace` are imported to replace ``'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'``. +This approach uses a [generator expression][generator-expression] to lowercase, clean, strip, and split the input phrase into words. +The words generator is then consumed by [`collections.Counter()`][collections-counter], which counts up the words. +For convenience, [`string.punctuation`][string-punctuation] and [`string.whitespace`][string-whitespace] are imported to replace ``'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'``. -Alternatively, `collections.defaultdict()` can be used in place of `Counter()`, but requires that the generator be iterated through in an explicit loop: +Alternatively, [`collections.defaultdict()`][collections-defaultdict] can be used in place of `Counter()`, but requires that the generator be iterated through in an explicit loop: ```python @@ -235,11 +235,11 @@ def count_words(sentence): ``` Regular Expressions have an almost endless variety. -This approach shows several different regular expression in combination with several different `re` module methods. +This approach shows several different regular expression in combination with several different [`re` module][re-module] methods. -1. `re.finditer()` to return a lazy iterator that is then fed to `collections.Counter()`. -2. `re.findall()` to return a list that is fed to `collections.Counter()` -3. `re.sub()` and `re.split()`to return a generator that is fed to `collections.Counter()`. +1. [`re.finditer()`][re-finditer] to return a lazy iterator that is then fed to [`collections.Counter()`][collections-counter]. +2. [`re.findall()`][re-findall] to return a list that is fed to `collections.Counter()` +3. [`re.sub()`][re-sub] and [`re.split()`][re-split] to return a generator that is fed to `collections.Counter()`. For all the details on these variations, take a look at the [Using the `re` Module][approach-using-the-re-module] approach. @@ -258,11 +258,11 @@ def count_words(phrase): return results ``` -This approach uses the (somewhat unusual) `str.translate()` to filter out unwanted characters. +This approach uses the (somewhat unusual) [`str.translate()`][str-translate] to filter out unwanted characters. `collections.Counter` is then used to count the words. -The generator expression uses an assignment operator (_othewise know as the "walrus" operator `:=`_) to ensure that empty strings are excluded from the count. +The [generator expression][generator-expression] uses [`:=`, the assignment operator][assignment-expression] (_otherwise known as the "walrus" operator_), to ensure that empty strings are excluded from the count. For more details, see the [Using `str.translate()` with `collections.counter()`][approach-str-translate-with-counter] approach. @@ -285,8 +285,8 @@ def count_words(sentence): return Counter(words) ``` -This approach uses the built-in `filter()` to clean the phrase and `collections.Counter()` to count the words. -Filter is fed the same general generator expression that uses `str.replace()`, `str.lower()`, and `str.split()` seen in other approaches. +This approach uses the built-in `filter()` to clean the phrase and [`collections.Counter()`][collections-counter] to count the words. +`filter()` is fed the same general generator expression that uses `str.replace()`, `str.lower()`, and `str.split()` seen in other approaches. For more information, read the [Filter with `collections.Counter()`][approach-filter-with-counter] approach. @@ -308,4 +308,27 @@ To compare the performance and other tradeoffs of the approaches, take a look at [approach-str-translate-with-counter]: https://exercism.org/tracks/python/exercises/word-count/approaches/str-translate-with-counter [approach-string-iteration-with-dict]: https://exercism.org/tracks/python/exercises/word-count/approaches/string-iteration-with-dict [approach-using-the-re-module]: https://exercism.org/tracks/python/exercises/word-count/approaches/using-the-re-module -[article-performance]:https://exercism.org/tracks/python/exercises/word-count/articles/performance +[article-performance]: https://exercism.org/tracks/python/exercises/word-count/articles/performance + +[assignment-expression]: https://docs.python.org/3/reference/expressions.html#assignment-expressions +[collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter +[collections-defaultdict]: https://docs.python.org/3/library/collections.html#collections.defaultdict +[dict-comprehension]: https://www.learnbyexample.org/python-dictionary-comprehension/ +[dict-get]: https://docs.python.org/3/builtins/stdtypes.html#dict.get +[dict-setdefault]: https://docs.python.org/3/builtins/stdtypes.html#dict.setdefault +[collections-module]: https://docs.python.org/3/library/collections.html +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[list-comprehension]: https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ +[re-findall]: https://docs.python.org/3/library/re.html#re.findall +[re-finditer]: https://docs.python.org/3/library/re.html#re.finditer +[re-module]: https://docs.python.org/3/library/re.html +[re-split]: https://docs.python.org/3/library/re.html#re.split +[re-sub]: https://docs.python.org/3/library/re.html#re.sub +[string-punctuation]: https://docs.python.org/3/library/string.html#string.punctuation +[string-whitespace]: https://docs.python.org/3/library/string.html#string.whitespace +[str-count]: https://docs.python.org/3/builtins/stdtypes.html#str.count +[str-lower]: https://docs.python.org/3/builtins/stdtypes.html#str.lower +[str-replace]: https://docs.python.org/3/builtins/stdtypes.html#str.replace +[str-split]: https://docs.python.org/3/builtins/stdtypes.html#str.split +[str-strip]: https://docs.python.org/3/builtins/stdtypes.html#str.strip +[str-translate]: https://docs.python.org/3/builtins/stdtypes.html#str.translate diff --git a/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md b/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md index 7dd2614d6b..5d9b641d98 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-collections/content.md @@ -17,14 +17,14 @@ def count_words(phrase): return Counter(words) ``` -This approach uses a `generator expression` to lowercase, clean, strip, and split the input phrase into words. +This approach uses a [generator expression][generator-expression] to lowercase, clean, strip, and split the input phrase into words. -Words is then consumed by the `Counter()` from the collections module, which counts up the words. +Words is then consumed by the [`Counter()`][collections-counter] from the [collections module][collections-module], which counts up the words. -For convenience, `string.punctuation` and `string.whitespace` are imported to replace ``'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'``. +For convenience, [`string.punctuation`][string-punctuation] and [`string.whitespace`][string-whitespace] are imported to replace ``'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'``. -Alternatively, `collections.defaultdict()` can be used, but requires that the words generator be iterated through in an explicit loop: +Alternatively, [`collections.defaultdict()`][collections-defaultdict] can be used, but requires that the words generator be iterated through in an explicit loop: ```python from string import punctuation, whitespace @@ -33,16 +33,26 @@ from collections import defaultdict IGNORE = punctuation + whitespace def count_words(phrase): - words = (word.strip(IGNORE) for word in - phrase.replace(',', ' ') + words = (word.strip(IGNORE) + for word in phrase + .replace(',', ' ') .replace('_', ' ') .lower() - .split() if word) + .split() + if word) counts = defaultdict(int) for word in words: - counts[word] +=1 + counts[word] += 1 return counts ``` + + +[collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter +[collections-defaultdict]: https://docs.python.org/3/library/collections.html#collections.defaultdict +[collections-module]: https://docs.python.org/3/library/collections.html +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[string-punctuation]: https://docs.python.org/3/library/string.html#string.punctuation +[string-whitespace]: https://docs.python.org/3/library/string.html#string.whitespace diff --git a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md index c9873db3c4..656e61fa07 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md @@ -25,8 +25,14 @@ def count_words(phrase): return {word : cleaned.count(word) for word in cleaned} ``` -This approach replaces the `for` loop in the previous approach with a `list comprehension`. +This approach replaces the `for` loop in the previous approach with a [list comprehension][list-comprehension]. -The `dictionary comprehension` then processes the words list, calling word.count(word) for each word (key) in the words list. +The [dictionary comprehension][dict-comprehension] then processes the words list, calling [`.count(word)`][str-count] for each word (key) in the words list. -Note that a `generator expression` cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. +Note that a [generator expression][generator-expression] cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. + + +[dict-comprehension]: https://www.learnbyexample.org/python-dictionary-comprehension/ +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[list-comprehension]: https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ +[str-count]: https://docs.python.org/3/builtins/stdtypes.html#str.count diff --git a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md index e347f6ff77..9d1f6dc366 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md @@ -23,6 +23,9 @@ def count_words(phrase): This approach replaces unwanted characters and lowercases the phrase before splitting it into a word list. -It then loops through the word list and uses `str.strip()` to remove characters from the `IGNORE` string. +It then loops through the word list and uses [`str.strip()`][str-strip] to remove characters from the `IGNORE` string. If there is a word left after the `str.strip()` operation, it is added to the _counts_ dictionary. + + +[str-strip]: https://docs.python.org/3/builtins/stdtypes.html#str.strip diff --git a/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md b/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md index e0d966b326..cf9f9d79fe 100644 --- a/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md +++ b/exercises/practice/word-count/.approaches/str-translate-with-counter/content.md @@ -12,8 +12,14 @@ def count_words(phrase): return results ``` -This approach (somewhat unusually) uses `str.translate()` to filter out unwanted characters. +This approach (somewhat unusually) uses [`str.translate()`][str-translate] to filter out unwanted characters. -`collections.Counter` is then used to count the words. +[`collections.Counter`][collections-counter] is then used to count the words. -The generator expression uses an assignment operator (_otherwise know as the "walrus" operator `:=`_) to ensure that empty strings are excluded from the count. +The [generator expression][generator-expression] uses [`:=`, the assignment operator][assignment-expression] (_otherwise known as the "walrus" operator_), to ensure that empty strings are excluded from the count. + + +[assignment-expression]: https://docs.python.org/3/reference/expressions.html#assignment-expressions +[collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[str-translate]: https://docs.python.org/3/builtins/stdtypes.html#str.translate diff --git a/exercises/practice/word-count/.approaches/using-the-re-module/content.md b/exercises/practice/word-count/.approaches/using-the-re-module/content.md index d0d1133b0d..4a514c47a1 100644 --- a/exercises/practice/word-count/.approaches/using-the-re-module/content.md +++ b/exercises/practice/word-count/.approaches/using-the-re-module/content.md @@ -34,10 +34,18 @@ def count_words(sentence): There are many variations that can be used in a regular expressions. -This approach shows several different regexs, in combination with several different `re` methods. +This approach shows several different regexes, in combination with several different [`re` module][re-module] methods. -The first variation uses `re.finditer()` to return a lazy iterator that is then fed to `collections.Counter`. +The first variation uses [`re.finditer()`][re-finditer] to return a lazy iterator that is then fed to [`collections.Counter`][collections-counter]. -The second variation uses `re.findall()` to return a list that is fed to `collections.Counter`. +The second variation uses [`re.findall()`][re-findall] to return a list that is fed to `collections.Counter`. -The final variation uses `re.sub()` and `re.split()` to return a generator that is fed to `collections.Counter`. +The final variation uses [`re.sub()`][re-sub] and [`re.split()`][re-split] to return a generator that is fed to `collections.Counter`. + + +[collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter +[re-findall]: https://docs.python.org/3/library/re.html#re.findall +[re-finditer]: https://docs.python.org/3/library/re.html#re.finditer +[re-module]: https://docs.python.org/3/library/re.html +[re-split]: https://docs.python.org/3/library/re.html#re.split +[re-sub]: https://docs.python.org/3/library/re.html#re.sub From 65aa585069213b6057607628fc2b54caaee8bd22 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:03:47 -0500 Subject: [PATCH 4/9] Add `filter-with-counter` approach explanation also update contributor information in `config.json` --- .../word-count/.approaches/config.json | 20 +++++++----- .../filter-with-counter/content.md | 31 ++++++++++++++++--- .../filter-with-counter/snippet.txt | 2 +- .../word-count/.approaches/introduction.md | 13 ++++---- 4 files changed, 48 insertions(+), 18 deletions(-) diff --git a/exercises/practice/word-count/.approaches/config.json b/exercises/practice/word-count/.approaches/config.json index 9682410535..bbee96ba97 100644 --- a/exercises/practice/word-count/.approaches/config.json +++ b/exercises/practice/word-count/.approaches/config.json @@ -1,6 +1,7 @@ { "introduction": { - "authors": ["bethanyg"] + "authors": ["bethanyg"], + "contributors": ["yrahcaz7"] }, "approaches": [ { @@ -15,42 +16,47 @@ "slug": "str-replace-with-dict", "title": "String Replace with Dictionary", "blurb": "Use str.replace and str.strip to filter out punctuation and sum word counts with a dict.", - "authors": ["bethanyg"] + "authors": ["bethanyg"], + "contributors": ["yrahcaz7"] }, { "uuid": "3d5d629f-58b6-43c5-9470-30b30b193892", "slug": "str-replace-with-comprehensions", "title": "String Replace with Comprehensions", "blurb": "Use str.replace and str.strip to filter out punctuation and sum word counts with comprehensions.", - "authors": ["bethanyg"] + "authors": ["bethanyg"], + "contributors": ["yrahcaz7"] }, { "uuid": "373182b1-8d21-4ee6-aa49-94ff6a9c57a1", "slug": "str-replace-with-collections", "title": "String Replace with Collections", "blurb": "Use str.replace and str.strip to filter out punctuation and let collections.Counter do the rest.", - "authors": ["bethanyg"] + "authors": ["bethanyg"], + "contributors": ["yrahcaz7"] }, { "uuid": "2afed504-500d-4415-a507-b78311bde777", "slug": "using-the-re-module", "title": "Using the re Module", "blurb": "Python's re module is both versatile and powerful.", - "authors": ["bethanyg"] + "authors": ["bethanyg"], + "contributors": ["yrahcaz7"] }, { "uuid": "0aa44eec-1c71-4937-8e3f-c45cbba22cc1", "slug": "str-translate-with-counter", "title": "String Translate with Counter", "blurb": "Use str.translate to filter out punctuation and then tally words with collections.Counter.", - "authors": ["bethanyg"] + "authors": ["bethanyg"], + "contributors": ["yrahcaz7"] }, { "uuid": "182463b2-fcfa-4445-967c-8b185b7853c9", "slug": "filter-with-counter", "title": "Filter with Counter", "blurb": "Use the built-in filter function to clean the sentence and collections.Counter to count the words.", - "authors": ["bethanyg"] + "authors": ["bethanyg", "yrahcaz7"] } ] } diff --git a/exercises/practice/word-count/.approaches/filter-with-counter/content.md b/exercises/practice/word-count/.approaches/filter-with-counter/content.md index 06e56fb77c..9a38c62092 100644 --- a/exercises/practice/word-count/.approaches/filter-with-counter/content.md +++ b/exercises/practice/word-count/.approaches/filter-with-counter/content.md @@ -1,17 +1,40 @@ -# Filter with Counter +# `filter()` with `collections.Counter()` ```python from collections import Counter -import string +from string import punctuation def count_words(sentence): words = filter(None, ( - word.strip(string.punctuation) + word.strip(punctuation) for word in sentence .lower() - .replace("_"," ") + .replace("_", " ") .replace(",", " ") .split() )) return Counter(words) ``` + +This approach begins by lowercasing the input sentence with [`str.lower()`][str-lower] and cleaning the input using [`str.replace()`][str-replace]. +It then splits the sentence into words and iterates over them using [`str.split()`][str-split] and a [generator expression][generator-expression]. + +For each word in the sentence, any leftover punctuation is removed using [`str.strip()`][str-strip] and [`string.punctuation`][string-punctuation]. +(Importing `punctuation` is only for convenience, a string containing ``!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`` would work as well.) + +Since the punctuation removal may leave empty strings, the generator expression is fed into [`filter()`][builtin-filter] with `None` as the first argument, which makes `filter()` discard any items that evaluate to `False` (i.e., items that are "falsy"). +An alternative would be to provide the [lambda][lambda] expression `lambda item: item` as the first argument instead of `None`, which would yield the same results. + +Once the words are `filter`ed, a [`Counter`][collections-counter] from the [`collections` module][collections-module] is constructed from the resulting iterator. Since `Counter`s are a subclass of dictionaries, the `Counter` can then be directly returned as the result. + + +[builtin-filter]: https://docs.python.org/3/builtins/functions.html#filter +[collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter +[collections-module]: https://docs.python.org/3/library/collections.html +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[lambda]: https://docs.python.org/3/glossary.html#term-lambda +[string-punctuation]: https://docs.python.org/3/library/string.html#string.punctuation +[str-lower]: https://docs.python.org/3/builtins/stdtypes.html#str.lower +[str-replace]: https://docs.python.org/3/builtins/stdtypes.html#str.replace +[str-split]: https://docs.python.org/3/builtins/stdtypes.html#str.split +[str-strip]: https://docs.python.org/3/builtins/stdtypes.html#str.strip diff --git a/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt b/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt index 2c6d303db3..847b21e310 100644 --- a/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt +++ b/exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt @@ -1,6 +1,6 @@ def count_words(sentence): words = filter(None, ( word.strip(string.punctuation) - for word in sentence.lower().replace("_"," ").replace(",", " ").split() + for word in sentence.lower().replace("_", " ").replace(",", " ").split() )) return Counter(words) diff --git a/exercises/practice/word-count/.approaches/introduction.md b/exercises/practice/word-count/.approaches/introduction.md index ae2b05e278..10d0feb906 100644 --- a/exercises/practice/word-count/.approaches/introduction.md +++ b/exercises/practice/word-count/.approaches/introduction.md @@ -271,25 +271,25 @@ For more details, see the [Using `str.translate()` with `collections.counter()`] ```python from collections import Counter -import string +from string import punctuation def count_words(sentence): words = filter(None, ( - word.strip(string.punctuation) + word.strip(punctuation) for word in sentence .lower() - .replace("_"," ") + .replace("_", " ") .replace(",", " ") .split() )) return Counter(words) ``` -This approach uses the built-in `filter()` to clean the phrase and [`collections.Counter()`][collections-counter] to count the words. +This approach uses the built-in [`filter()`][builtin-filter] to clean the input and [`collections.Counter()`][collections-counter] to count the words. `filter()` is fed the same general generator expression that uses `str.replace()`, `str.lower()`, and `str.split()` seen in other approaches. -For more information, read the [Filter with `collections.Counter()`][approach-filter-with-counter] approach. +For more information, read the [`filter()` with `collections.Counter()`][approach-filter-with-counter] approach. ## Which approach to use? @@ -311,12 +311,13 @@ To compare the performance and other tradeoffs of the approaches, take a look at [article-performance]: https://exercism.org/tracks/python/exercises/word-count/articles/performance [assignment-expression]: https://docs.python.org/3/reference/expressions.html#assignment-expressions +[builtin-filter]: https://docs.python.org/3/builtins/functions.html#filter [collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter [collections-defaultdict]: https://docs.python.org/3/library/collections.html#collections.defaultdict +[collections-module]: https://docs.python.org/3/library/collections.html [dict-comprehension]: https://www.learnbyexample.org/python-dictionary-comprehension/ [dict-get]: https://docs.python.org/3/builtins/stdtypes.html#dict.get [dict-setdefault]: https://docs.python.org/3/builtins/stdtypes.html#dict.setdefault -[collections-module]: https://docs.python.org/3/library/collections.html [generator-expression]: https://dbader.org/blog/python-generator-expressions [list-comprehension]: https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ [re-findall]: https://docs.python.org/3/library/re.html#re.findall From 7b6f8b1069eff76543fbd072848596056658849c Mon Sep 17 00:00:00 2001 From: Yrahcaz <74512479+Yrahcaz7@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:17:54 -0500 Subject: [PATCH 5/9] Apply batched suggestions from code review Co-authored-by: BethanyG --- exercises/practice/word-count/.approaches/introduction.md | 2 +- .../word-count/.approaches/str-replace-with-dict/content.md | 2 +- .../word-count/.approaches/using-the-re-module/content.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/exercises/practice/word-count/.approaches/introduction.md b/exercises/practice/word-count/.approaches/introduction.md index 10d0feb906..f6294c0be4 100644 --- a/exercises/practice/word-count/.approaches/introduction.md +++ b/exercises/practice/word-count/.approaches/introduction.md @@ -71,7 +71,7 @@ def count_words(sentence): return word_list ``` -This approach avoids splitting the phrase into a word list by iterating over each _character_ in the sentence to determine if it belongs in a valid word (_only letters and numbers are allowed_). +This approach avoids splitting the phrase into a word list by iterating over each _code point_ in the sentence to determine if it belongs in a valid word (_only letters and numbers are allowed_). As each valid word is built up, it is added to the dictionary. Using `word_list.get()` allows for setting newly added words to value 1 while incrementing values for words already added to the dictionary. diff --git a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md index 9d1f6dc366..f4b9898241 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md @@ -9,7 +9,7 @@ def count_words(phrase): .lower() .split()) # Returns a list, ready for further processing. - counts = {} + counts = {} #<-- note this is a mutable dict. for word in words: word = word.strip(IGNORE) diff --git a/exercises/practice/word-count/.approaches/using-the-re-module/content.md b/exercises/practice/word-count/.approaches/using-the-re-module/content.md index 4a514c47a1..d8dc646640 100644 --- a/exercises/practice/word-count/.approaches/using-the-re-module/content.md +++ b/exercises/practice/word-count/.approaches/using-the-re-module/content.md @@ -38,7 +38,7 @@ This approach shows several different regexes, in combination with several diffe The first variation uses [`re.finditer()`][re-finditer] to return a lazy iterator that is then fed to [`collections.Counter`][collections-counter]. -The second variation uses [`re.findall()`][re-findall] to return a list that is fed to `collections.Counter`. +The second variation uses [`re.findall()`][re-findall] to return a `list` that is fed to `collections.Counter`. The final variation uses [`re.sub()`][re-sub] and [`re.split()`][re-split] to return a generator that is fed to `collections.Counter`. From ac44b517ffe5fffad05d1036d9bee867d13cd169 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:25:43 -0500 Subject: [PATCH 6/9] add a variant to `filter-with-counter` --- .../filter-with-counter/content.md | 24 ++++++++++++++++++- .../str-replace-with-dict/content.md | 2 +- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/exercises/practice/word-count/.approaches/filter-with-counter/content.md b/exercises/practice/word-count/.approaches/filter-with-counter/content.md index 9a38c62092..cbcf3082c8 100644 --- a/exercises/practice/word-count/.approaches/filter-with-counter/content.md +++ b/exercises/practice/word-count/.approaches/filter-with-counter/content.md @@ -20,13 +20,35 @@ This approach begins by lowercasing the input sentence with [`str.lower()`][str- It then splits the sentence into words and iterates over them using [`str.split()`][str-split] and a [generator expression][generator-expression]. For each word in the sentence, any leftover punctuation is removed using [`str.strip()`][str-strip] and [`string.punctuation`][string-punctuation]. -(Importing `punctuation` is only for convenience, a string containing ``!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`` would work as well.) +(Importing `punctuation` is only for convenience, a string containing ``!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`` would work as well, as long as the input only contains ASCII characters.) Since the punctuation removal may leave empty strings, the generator expression is fed into [`filter()`][builtin-filter] with `None` as the first argument, which makes `filter()` discard any items that evaluate to `False` (i.e., items that are "falsy"). An alternative would be to provide the [lambda][lambda] expression `lambda item: item` as the first argument instead of `None`, which would yield the same results. Once the words are `filter`ed, a [`Counter`][collections-counter] from the [`collections` module][collections-module] is constructed from the resulting iterator. Since `Counter`s are a subclass of dictionaries, the `Counter` can then be directly returned as the result. +## Variation 1 + +Alternatively, an `if` clause could be used instead of `filter()`, and the result can be directly fed into `Counter()`: + +```python +from collections import Counter +from string import punctuation + +def count_words(sentence): + return Counter( + word.strip(punctuation) + for word in sentence + .lower() + .replace("_", " ") + .replace(",", " ") + .split() + if word.strip(punctuation) + ) +``` + +However, this has extra overhead from calling `strip()` twice and is debatably less readable. + [builtin-filter]: https://docs.python.org/3/builtins/functions.html#filter [collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter diff --git a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md index f4b9898241..de8b9360b1 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md @@ -9,7 +9,7 @@ def count_words(phrase): .lower() .split()) # Returns a list, ready for further processing. - counts = {} #<-- note this is a mutable dict. + counts = {} # <-- note this is a mutable dict. for word in words: word = word.strip(IGNORE) From c27699cc857fb41b7d4e3c784e96d2ce0f25d421 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:36:31 -0500 Subject: [PATCH 7/9] move generator expression note also clarify "String Replace with Dictionary" -> "String Replace with Mutable Dictionary" --- exercises/practice/word-count/.approaches/config.json | 2 +- exercises/practice/word-count/.approaches/introduction.md | 7 ------- .../str-replace-with-comprehensions/content.md | 8 ++++++-- .../.approaches/str-replace-with-dict/content.md | 2 +- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/exercises/practice/word-count/.approaches/config.json b/exercises/practice/word-count/.approaches/config.json index bbee96ba97..868456afa2 100644 --- a/exercises/practice/word-count/.approaches/config.json +++ b/exercises/practice/word-count/.approaches/config.json @@ -14,7 +14,7 @@ { "uuid": "5a5f4f89-b016-48ed-9316-a49cadf9735f", "slug": "str-replace-with-dict", - "title": "String Replace with Dictionary", + "title": "String Replace with Mutable Dictionary", "blurb": "Use str.replace and str.strip to filter out punctuation and sum word counts with a dict.", "authors": ["bethanyg"], "contributors": ["yrahcaz7"] diff --git a/exercises/practice/word-count/.approaches/introduction.md b/exercises/practice/word-count/.approaches/introduction.md index f6294c0be4..75bbe09855 100644 --- a/exercises/practice/word-count/.approaches/introduction.md +++ b/exercises/practice/word-count/.approaches/introduction.md @@ -140,13 +140,6 @@ def count_words(phrase): This approach replaces the `for` loop in the previous approach with a [`list comprehension`][list-comprehension]. The [`dictionary comprehension`][dict-comprehension] then processes the words list, calling [`.count(word)`][str-count] for each word (key) in the words list. - -~~~~exercism/note -A [generator expression][generator-expression] cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. -Generator expressions are not indexable, and can only be iterated through once. -~~~~ - - For more information, read the [`str.replace()` with Comprehensions][approach-str-replace-with-comprehensions] approach. diff --git a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md index 656e61fa07..20721e3958 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-comprehensions/content.md @@ -29,10 +29,14 @@ This approach replaces the `for` loop in the previous approach with a [list comp The [dictionary comprehension][dict-comprehension] then processes the words list, calling [`.count(word)`][str-count] for each word (key) in the words list. -Note that a [generator expression][generator-expression] cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. +~~~~exercism/note +A [generator expression][generator-expression] cannot be used in this scenario due to the use of `count()` in the dictionary comprehension. +Generator expressions are not indexable, and can only be iterated through once. + +[generator-expression]: https://dbader.org/blog/python-generator-expressions +~~~~ [dict-comprehension]: https://www.learnbyexample.org/python-dictionary-comprehension/ -[generator-expression]: https://dbader.org/blog/python-generator-expressions [list-comprehension]: https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ [str-count]: https://docs.python.org/3/builtins/stdtypes.html#str.count diff --git a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md index de8b9360b1..bf7b8129b3 100644 --- a/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md +++ b/exercises/practice/word-count/.approaches/str-replace-with-dict/content.md @@ -1,4 +1,4 @@ -# String Replace with Dictionary +# String Replace with Mutable Dictionary ```python IGNORE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' From 055667ee6cbe3449c30321fbbee5fb0ca7db05a6 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:26:03 -0500 Subject: [PATCH 8/9] fix carriage return (\r) -> line feed (\n) --- exercises/practice/word-count/.approaches/introduction.md | 2 +- .../word-count/.approaches/str-iteration-with-dict/content.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/exercises/practice/word-count/.approaches/introduction.md b/exercises/practice/word-count/.approaches/introduction.md index 75bbe09855..bb522c4385 100644 --- a/exercises/practice/word-count/.approaches/introduction.md +++ b/exercises/practice/word-count/.approaches/introduction.md @@ -55,7 +55,7 @@ A complex regular expression that involves backtracking can also be much slower ```python def count_words(sentence): - sentence = sentence.lower() + '\n' # Lowercase the sentence and add a carriage return to it. + sentence = sentence.lower() + '\n' # Lowercase the sentence and add a line feed to it. word_list = {} new_word = '' diff --git a/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md b/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md index 6a372289be..ecec0a071d 100644 --- a/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md +++ b/exercises/practice/word-count/.approaches/str-iteration-with-dict/content.md @@ -2,7 +2,7 @@ ```python def count_words(sentence): - sentence = sentence.lower() + '\n' # Lowercase the sentence and add a carriage return to it. + sentence = sentence.lower() + '\n' # Lowercase the sentence and add a line feed to it. word_list = {} new_word = '' From 79f572bba7fbb3f89f39487a2eedc8fee9bbb51b Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:51:34 -0500 Subject: [PATCH 9/9] add performance note to the regex approach --- .../practice/word-count/.approaches/introduction.md | 2 +- .../.approaches/using-the-re-module/content.md | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/exercises/practice/word-count/.approaches/introduction.md b/exercises/practice/word-count/.approaches/introduction.md index bb522c4385..13a45481e0 100644 --- a/exercises/practice/word-count/.approaches/introduction.md +++ b/exercises/practice/word-count/.approaches/introduction.md @@ -291,7 +291,7 @@ The most performant of these approaches is __ for longer text, and __ for smalle Overall, using `str.replace()` with a `collections.Counter()` or `dict` might be the most readable to those unfamiliar with regex, and iterating through the string might be more readable to those not familiar with Python. -To compare the performance and other tradeoffs of the approaches, take a look at the [Performance article][article-performance]. +To compare the performance and other tradeoffs of the approaches, take a look at the [performance article][article-performance]. [approach-filter-with-counter]: https://exercism.org/tracks/python/exercises/word-count/approaches/filter-with-counter diff --git a/exercises/practice/word-count/.approaches/using-the-re-module/content.md b/exercises/practice/word-count/.approaches/using-the-re-module/content.md index d8dc646640..51152841cd 100644 --- a/exercises/practice/word-count/.approaches/using-the-re-module/content.md +++ b/exercises/practice/word-count/.approaches/using-the-re-module/content.md @@ -1,4 +1,4 @@ -# Using the Re Module +# Using the `re` Module ```python import re @@ -32,9 +32,7 @@ def count_words(sentence): return Counter(words) ``` -There are many variations that can be used in a regular expressions. - -This approach shows several different regexes, in combination with several different [`re` module][re-module] methods. +There are many variations of the regular expression approach that use several different regexes, in combination with several different [`re` module][re-module] methods. The first variation uses [`re.finditer()`][re-finditer] to return a lazy iterator that is then fed to [`collections.Counter`][collections-counter]. @@ -42,7 +40,11 @@ The second variation uses [`re.findall()`][re-findall] to return a `list` that i The final variation uses [`re.sub()`][re-sub] and [`re.split()`][re-split] to return a generator that is fed to `collections.Counter`. +Although these solutions may be shorter than some of the other approaches, importing the `re` module causes a large amount of overhead, and the regex functions are often slower than other solutions (especially `re.sub()`). +For more detail, take a look at the [performance article][article-performance]. + +[article-performance]: https://exercism.org/tracks/python/exercises/word-count/articles/performance [collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter [re-findall]: https://docs.python.org/3/library/re.html#re.findall [re-finditer]: https://docs.python.org/3/library/re.html#re.finditer