-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[Wordy] Add tuple-and-index approach
#4202
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
Open
Yrahcaz7
wants to merge
3
commits into
exercism:main
Choose a base branch
from
Yrahcaz7:wordy-new-approach
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.
Open
Changes from all commits
Commits
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
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
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
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
81 changes: 81 additions & 0 deletions
81
exercises/practice/wordy/.approaches/tuple-and-index/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,81 @@ | ||
| # Tuples with `sequence.index()` | ||
|
|
||
| ```python | ||
| OPERATOR_WORDS = ("plus", "minus", "multiplied", "divided") | ||
|
|
||
| EXTRA_OPERATOR_WORDS = (None, None, "by", "by") | ||
|
|
||
|
|
||
| def answer(question): | ||
| if not question.startswith("What is ") or not question.endswith("?"): | ||
| raise ValueError("syntax error") | ||
|
|
||
| words = question[:-1].split(" ") | ||
| result = str_to_int(words[2]) | ||
| index = 3 | ||
|
|
||
| while index < len(words): | ||
| try: | ||
| operator_index = OPERATOR_WORDS.index(words[index]) | ||
| except ValueError: | ||
| str_to_int(words[index], "unknown operation") | ||
| raise ValueError("syntax error") | ||
|
|
||
| operand_index = index + 1 | ||
| if EXTRA_OPERATOR_WORDS[operator_index] is not None: | ||
| if index + 1 >= len(words) or words[index + 1] != EXTRA_OPERATOR_WORDS[operator_index]: | ||
| raise ValueError("syntax error") | ||
| operand_index += 1 | ||
|
|
||
| if operand_index >= len(words): | ||
| raise ValueError("syntax error") | ||
|
|
||
| operand = str_to_int(words[operand_index]) | ||
| match operator_index: | ||
| case 0: result += operand | ||
| case 1: result -= operand | ||
| case 2: result *= operand | ||
| case 3: result //= operand | ||
|
|
||
| index = operand_index + 1 | ||
|
|
||
| return result | ||
|
|
||
|
|
||
| def str_to_int(string, err_msg = "syntax error"): | ||
| try: | ||
| return int(string) | ||
| except ValueError: | ||
| raise ValueError(err_msg) | ||
| ``` | ||
|
|
||
| This approach starts with declaring the `OPERATOR_WORDS` tuple, which contains the first word of each phrase that indicates an operator. | ||
| The `EXTRA_OPERATOR_WORDS` tuple contains the second word of each phrase if it exists, and [`None`][none] otherwise. | ||
|
|
||
| In `answer()`, we start by checking that the question starts with "What is " and ends with "?". | ||
| (Unlike many other approaches, it does not rely on explicitly checking for "cubed".) | ||
| Next, the question is `split` into a `words` list, excluding the trailing "?". | ||
|
|
||
| Then we call the helper function `str_to_int()` to initialize `result` to the first number in the question, or raise a `ValueError` if the third "word" is not a number. | ||
| Next, we start the while loop with `index` set to `3`, indicating that we have finished parsing the first `3` words ("What", "is", and the number). | ||
|
|
||
| Inside the loop, we use [`OPERATOR_WORDS.index()`][sequence-index-method] to get the index of the operator at index `index` of `words`. | ||
| If `words[index]` is not an operator word, the raised `ValueError` will be caught by the [`try-except`][handling-exceptions] statement, and the `except` block will determine the correct error to raise instead. | ||
|
|
||
| Next, we need to get the second operand for the operator (we already have `result` for the first one), so we set `operand_index = index + 1`. | ||
| However, some operator phrases are multiple words long, so we need to check if `EXTRA_OPERATOR_WORDS[operator_index] is not None`. | ||
| If there *is* an extra operator word, then we need to check if it is present as the next word in `words`. | ||
| If it is not present, we raise a `ValueError`, else we increment `operand_index` by `1` to get the correct index. | ||
|
|
||
| Here we call the helper function again, setting `operand` to the number at index `operand_index`, and raising a `ValueError` if it is not a number. | ||
| After this, the approach uses [structural pattern matching][structural-pattern-matching] to modify `result` using `+=`, `-=`, `*=`, or `//=` depending on the `operator_index`. | ||
| However, this section could easily be modified to use a similar method to any of the other approaches, such as an `if-elif-else` block or a tuple of `lambda`s. | ||
|
|
||
| At the end of the loop, we set `index` to `operand_index + 1`, as we have finished processing everything up to and including `operand_index`. | ||
| Then the loop continues until `index` reaches or exceeds `len(words)` or an uncaught error is raised. | ||
| When the loop ends, we know that we have finished processing the entire string, and thus we return `result`. | ||
|
|
||
| [handling-exceptions]: https://docs.python.org/3.11/tutorial/errors.html#handling-exceptions | ||
| [none]: https://docs.python.org/3/library/constants.html#None | ||
| [sequence-index-method]: https://docs.python.org/3/library/stdtypes.html#sequence.index | ||
| [structural-pattern-matching]: https://peps.python.org/pep-0636/ | ||
8 changes: 8 additions & 0 deletions
8
exercises/practice/wordy/.approaches/tuple-and-index/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,8 @@ | ||
| OPERATOR_WORDS = ("plus", "minus", "multiplied", "divided") | ||
| EXTRA_OPERATOR_WORDS = (None, None, "by", "by") | ||
| ... | ||
| try: | ||
| operator_index = OPERATOR_WORDS.index(words[index]) | ||
| except ValueError: | ||
| str_to_int(words[index], "unknown operation") | ||
| raise ValueError("syntax error") |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You might want to name the helper function since this explanation is long enough to have to scroll back up to see the code.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good idea, but I'm not sure how to change the sentence to include that. Any change I try seems to make it read awkwardly...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about
Or is that just too much?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Its fine if it just doesn't work. It was just a thought - no need to cram it in if its not working.