Skip to content

Commit 80d7e43

Browse files
finished update to trigrams exercise
1 parent b2b0cbe commit 80d7e43

4 files changed

Lines changed: 376 additions & 29 deletions

File tree

‎source/exercises/trigrams/test_trigrams.py‎

Lines changed: 96 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,101 @@ def test_make_sentence():
143143
# check that there is not a space between the period and the last word.
144144
assert not sentence[-2].isspace()
145145

146-
147-
148-
146+
# the following tests are for the "make_words" function,
147+
# which takes a text string, and returns a list of words
148+
# It also cleans up the punctuation, while preserving things
149+
# like apostrophes, and capitalized "I".
150+
# you may choose to handle punctuation differently
151+
# feel free to adapt the tests to your choices
152+
153+
154+
# TEXT_WITH_PUNC = """
155+
# One night--it was on the twentieth of March, 1888--I was
156+
# returning from a journey to a patient (for I had now returned to
157+
# civil practice), when my way led me through Baker Street. As I
158+
# passed the well-remembered door, which must always be associated
159+
# in my mind with my wooing, and with the dark incidents of the
160+
# Study in Scarlet, I was seized with a keen desire to see Holmes
161+
# again, and to know how he was employing his extraordinary powers.
162+
# His rooms were brilliantly lit, and, even as I looked up, I saw
163+
# his tall, spare figure pass twice in a dark silhouette against
164+
# the blind.
165+
# """
166+
167+
168+
# def test_make_words_simple():
169+
# """
170+
# make sure the basics work!
171+
# """
172+
# all_words = trigrams.make_words("A really simple sentence.")
173+
174+
# assert len(all_words) == 4
175+
176+
177+
# def test_make_words_commas():
178+
# """
179+
# all commas should be removed
180+
# """
181+
# # put them all back together for easier checking
182+
# all_words = " ".join(trigrams.make_words(TEXT_WITH_PUNC))
183+
184+
# assert "," not in all_words
185+
186+
187+
# def test_make_words_parentheses():
188+
# """
189+
# all parenthesis should be removed
190+
# """
191+
# # put them all back together for easier checking
192+
# all_words = " ".join(trigrams.make_words(TEXT_WITH_PUNC))
193+
194+
# assert "(" not in all_words
195+
# assert ")" not in all_words
196+
197+
198+
# def test_make_words_dashes():
199+
# """
200+
# all dashes should be removed
201+
# """
202+
# # put them all back together for easier checking
203+
# all_words = " ".join(trigrams.make_words(TEXT_WITH_PUNC))
204+
205+
# assert "-" not in all_words
206+
207+
208+
# def test_make_words_I():
209+
# """
210+
# I should be capitalized
211+
# """
212+
# all_words = trigrams.make_words(TEXT_WITH_PUNC)
213+
214+
# assert "i" not in all_words
215+
# assert "I" in all_words
216+
217+
218+
# def test_make_words_single_quote():
219+
# """
220+
# no double quotes
221+
# no single quotes by themselves, but preserved when an apostrophe
222+
# """
223+
# # put them all back together for easier checking
224+
# text = """
225+
# "Not at all. The 'G' with the small 't' stands for
226+
# 'Gesellschaft,' which isn't the German for 'Company.'
227+
# """
228+
# all_words = trigrams.make_words(text)
229+
230+
# print(all_words)
231+
# # no double quotes
232+
# assert '"' not in " ".join(all_words)
233+
# # apostophe preserved
234+
# assert "isn't" in all_words
235+
236+
# # none of the words should start or end with a single quote
237+
# for word in all_words:
238+
# assert not word.startswith("'")
239+
# assert not word.endswith("'")
240+
241+
# assert False
149242

150243

‎source/exercises/trigrams/trigrams.rst‎

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -136,14 +136,15 @@ I’ll fire the signal and the fun will commence...
136136
Developing Your Solution
137137
========================
138138

139-
This assignment has two parts: the key one is the trigrams exercise itself, but you also need to do some text processing to get a full book in shape for processing.
139+
This assignment has two parts: the key one is the trigrams exercise itself, but you also need to do some text processing to get a full book in shape for the building the trigrams.
140140

141141
I suggest you write the trigrams part first; it's more interesting :-)
142142

143+
143144
Test Driven Development
144145
-----------------------
145146

146-
You've recently learned about unit testing and Test Driven Development (TDD). That's put that to work on this exercise. Remember that the key to TDD is that you first decide on what you need a piece of your code to do, then you write a test to check that it does that, and only then do you write the actual code itself.
147+
You've recently learned about unit testing and Test Driven Development (TDD). Let's put that to work on this exercise. Remember that the key to TDD is that you first decide on what you need a piece of your code to do, then you write a test to check that it does that, and only then do you write the actual code itself.
147148

148149
Because you're new to this, we're going to give you some tests to get you started. You'll find them in: :download:`test_trigrams.py <./test_trigrams.py>`, which should be with this assignment.
149150

@@ -173,20 +174,23 @@ To run the tests, use the ``pytest`` test runner: set your working directory the
173174
!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!
174175
======================== 1 error in 0.13s =========================
175176
176-
You should have gotten something like that error: it is indicating that the "trigrams" module does not exist -- which makes sense, as you haven't written in yet. So the first step is the create your code file: name it ``trigrams.py`` and put it in the same directory as the ``test_trigrams.py`` file. It can be empty for now. Now try running pytest again, and it should get farther: you'll have a lot of test failures, but the test should actually run. You should get something like:
177+
You should have gotten something like that error: it is indicating that the "trigrams" module does not exist -- which makes sense, as you haven't written it yet. So the first step is to create your code file: name it ``trigrams.py`` and put it in the same directory as the ``test_trigrams.py`` file. It can be empty for now. Now try running pytest again, and it should get farther: you'll have a lot of test failures, but the test should actually run. You should get something like:
177178
178179
.. code-block:: bash
179180
180-
...
181-
> tris = trigrams.build_trigram(IWISH)
182-
E AttributeError: module 'trigrams' has no attribute 'build_trigram'
183-
184-
test_trigrams.py:29: AttributeError
181+
test_trigrams.py:130: AttributeError
185182
====================== short test summary info =======================
186-
FAILED test_trigrams.py::test_trigrams_keys - AttributeError: modul...
187-
========================= 1 failed in 0.15s ==========================
183+
FAILED test_trigrams.py::test_trigrams_pairs - AttributeError: modu...
184+
FAILED test_trigrams.py::test_trigrams_following_words - AttributeE...
185+
FAILED test_trigrams.py::test_pick_random_pair - AttributeError: mo...
186+
FAILED test_trigrams.py::test_get_last_pair - AttributeError: modul...
187+
FAILED test_trigrams.py::test_get_random_follower - AttributeError:...
188+
FAILED test_trigrams.py::test_get_random_follower_not_there - Attri...
189+
FAILED test_trigrams.py::test_make_sentence - AttributeError: modul...
190+
========================= 7 failed in 0.18s ==========================
191+
188192
189-
You get an Attribute error, as you haven' defined anything in your ``trigrams.py`` file. But now it's time to actually work on the code!
193+
You get a bunch of AttributeErrors, as you haven't defined anything in your ``trigrams.py`` file. So now it's time to actually work on the code!
190194
191195
trigrams
192196
--------
@@ -216,7 +220,7 @@ You will find that example in the test file, so we can write tests against it:
216220
217221
.. code-block:: python
218222
219-
IWISH = ["I", "wish", "I", "may", "I", "wish", "I", "might"]
223+
IWISH = "I wish I may I wish I might".split()
220224
221225
222226
The trigrams structure
@@ -319,7 +323,7 @@ So contrary to the usual practice, an index can be helpful here:
319323
320324
For each pair in the text, you need to add it to the dict. But:
321325
322-
- ``words[i:i + 2]`` is a list with two words in it. Can that be used as a key in a dict? (Try it.) If not, how can you make a valid key out of it?
326+
- ``words[i:i + 2]`` is a list with two words in it. Can that be used as a key in a dict? (try it.) If not, how can you make a valid key out of it?
323327
324328
- As you loop through the text, you will collect pairs of words. Each time, a given pair may already be in the dict.
325329
@@ -382,7 +386,7 @@ and one that tests if the following word lists are correct:
382386
383387
Note that if the first test fails, almost certainly the second will too (the second test explicitly looks for all the same keys). That's OK. It's still good to keep them separate, because the first test could pass while the second one fails -- it's nice to know you've made progress!
384388
385-
If it seems like we have hard-coded a lot of detail in -- you are right. But this is quite deliberate. And it is why we chose such a simple set of words to start out with. If you want read a bit more about this approach, this blogger puts it nicely:
389+
If it seems like we have hard-coded a lot of detail into the tests -- you are right. But this is quite deliberate. And it is why we chose such a simple set of words to start out with. If you want to read a bit more about this approach, this blogger puts it nicely:
386390
`Write Explicit Tests <https://amir.rachum.com/blog/2017/01/14/explicit-tests/>`_
387391
388392
If both tests pass, you should now have code that will return a dict like we noted above::
@@ -400,7 +404,7 @@ Using the Trigrams dict
400404
401405
This is the fun part. Once you have a mapping of word pairs to following words, you can build up some new "fake" text. Re-read the previous sections again to remind yourself of the procedure. Here are a couple of additional hints and questions to consider:
402406
403-
- The ``random`` module <https://docs.python.org/3/library/random.html#module-random> is your friend here:
407+
- The ``random`` module: https://docs.python.org/3/library/random.html#module-random is your friend here:
404408
405409
.. code-block:: python
406410
@@ -412,14 +416,14 @@ This is the fun part. Once you have a mapping of word pairs to following words,
412416
# pick a random item from a sequence
413417
random.choice(a_list)
414418
415-
This is all pretty tricky to test -- after all, you are selecting random words -- you can't know what the result should be! There are two tactics you can take here.
419+
This is all pretty tricky to test -- after all, you are selecting random words -- you can't know what the result should be! There are two tactics you can take to test code with ``random`` calls in it.
416420
417421
Tactic one is to break you code down into pieces that you *can* test -- everything BUT the random choices.
418422
419423
Tactic two is to set the random seed before each test, to assure the same result.
420424
The built in ``random`` module `provides a way to set the seed <https://docs.python.org/3/library/random.html#random.seed>`_: the ``random.seed()`` function.
421425
422-
.. note:: Computers don't really make truly random numbers. What they do is compute a sequence of numbers that are statistically very much like random numbers, known as `"pseudo random numbers" <https://en.wikipedia.org/wiki/Pseudorandom_number_generator>`_. If you start with the same initial value, known as the "seed", then you will get the same sequence of numbers. `Random seed <https://en.wikipedia.org/wiki/Random_seed>`_
426+
.. note:: Computers don't really make truly random numbers. What they do is compute a sequence of numbers that are statistically very much like random numbers, known as `"pseudo random numbers" <https://en.wikipedia.org/wiki/Pseudorandom_number_generator>`_. If you start with the same initial value, known as the "seed", then you will get the same sequence of numbers (`random seed <https://en.wikipedia.org/wiki/Random_seed>`_).
423427
424428
The provided tests use both of these tactics.
425429
@@ -442,7 +446,7 @@ The provided tests use both of these tactics.
442446
443447
So you'll need to define a function: ``pick_random_pair()`` that takes your trigram dict as input, and returns a random key.
444448
445-
Note that the particular result in the test is using a particular algorithm -- if you use a different one, you might get a different pair -- but you should get the same one every time, so you can make the test check for that.
449+
Note that the particular result in the test is using a particular algorithm -- if you use a different one, you might get a different pair -- but since the seed is set, you should get the same one every time the test is run, so you can make the test check for the one your code returns.
446450
447451
Once you've got the first starting pair, you'll need to make your text,
448452
so you'll need a data structure to build it up in. You probably want to build it up in a list, appending one word at a time. You can join it together at the end with ``" ".join(the_list_of_words)``, which will make a string, separating the words with a space.
@@ -532,6 +536,8 @@ You now have the pieces you need to make some new text. Let's write a function t
532536
# check that there is not a space between the period and the last word.
533537
assert not sentence[-2].isspace()
534538
539+
Notice that this test did not set the random seed. Rather, it checked for various properties of the results, without checking for specific words. This is a helpful tactic -- have your tests check for what is important about the results, not necessarily the specific results.
540+
535541
You can now use the previous functions to make a ``make_sentence()`` function that passes these tests.
536542
537543
@@ -551,9 +557,7 @@ Hint: in a Project Gutenberg e-book, there is a line of text that starts with::
551557
552558
*** START OF THIS PROJECT GUTENBERG EBOOK
553559
554-
In the loop, you can process a single line of text to break it into words:
555-
556-
- calling ``.split()``
560+
In the loop, you can process a single line of text to break it into words by calling ``.split()``.
557561
558562
Optional steps to cleaning up the text:
559563
@@ -569,6 +573,9 @@ Be sure to use TDD as you develop the "clean up" code: write a test for one feat
569573
570574
Lather, rinse and repeat.
571575
576+
There are a number of tests for cleaning up the code commented out in the test file. Feel free to use these as a starting point.
577+
578+
572579
**Hints:**
573580
574581
The ``string`` methods are your friend here.
@@ -606,4 +613,8 @@ For instance, your ``__main__`` block might look something like:
606613
607614
print(new_text)
608615
616+
**Have Fun!**
617+
618+
619+
609620

0 commit comments

Comments
 (0)