Repository navigation
[Word Count] Adding Approach Docs #4352
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Yrahcaz7
wants to merge
9
commits into
exercism:main
Choose a base branch
from
Yrahcaz7:word-count-approaches
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+743
−0
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
967d5fa
Add files from old draft PR
Yrahcaz7 60e0767
formatting, spelling, and grammar fixes
Yrahcaz7 8d576e7
more formatting/spelling fixes & add links
Yrahcaz7 65aa585
Add `filter-with-counter` approach explanation
Yrahcaz7 7b6f8b1
Apply batched suggestions from code review
Yrahcaz7 ac44b51
add a variant to `filter-with-counter`
Yrahcaz7 c27699c
move generator expression note
Yrahcaz7 055667e
fix carriage return (\r) -> line feed (\n)
Yrahcaz7 79f572b
add performance note to the regex approach
Yrahcaz7 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| { | ||
| "introduction": { | ||
| "authors": ["bethanyg"], | ||
| "contributors": ["yrahcaz7"] | ||
| }, | ||
| "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 Mutable Dictionary", | ||
| "blurb": "Use str.replace and str.strip to filter out punctuation and sum word counts with a dict.", | ||
| "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"], | ||
| "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"], | ||
| "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"], | ||
| "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"], | ||
| "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", "yrahcaz7"] | ||
| } | ||
| ] | ||
| } |
62 changes: 62 additions & 0 deletions
62
exercises/practice/word-count/.approaches/filter-with-counter/content.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| # `filter()` with `collections.Counter()` | ||
|
|
||
| ```python | ||
| from collections import Counter | ||
| from string import punctuation | ||
|
|
||
| def count_words(sentence): | ||
| words = filter(None, ( | ||
| word.strip(punctuation) | ||
| for word in sentence | ||
| .lower() | ||
| .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, 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 | ||
| [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 | ||
6 changes: 6 additions & 0 deletions
6
exercises/practice/word-count/.approaches/filter-with-counter/snippet.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| def count_words(sentence): | ||
| words = filter(None, ( | ||
| word.strip(string.punctuation) | ||
| for word in sentence.lower().replace("_", " ").replace(",", " ").split() | ||
| )) | ||
| return Counter(words) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.