Skip to content

Commit 74c8535

Browse files
got a start on a TDD trigrams
1 parent 4806b0b commit 74c8535

2 files changed

Lines changed: 186 additions & 30 deletions

File tree

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
test code for the "trigrams" exercise
5+
6+
NOTE: This is NOT a complete set of tests! You will want to add more of
7+
your own to get complete coverage.
8+
9+
As you develop your code, if you are about to add a feature, or think
10+
of an edge case:
11+
12+
Write a new test for that first!
13+
14+
Also note that you may want to do some different things with processing
15+
the text -- if so, then update the tests (and add more) to reflect how you want your code to work.
16+
"""
17+
18+
# this is expecting a "trigrams.py" file with your code in it.
19+
20+
import random
21+
import trigrams
22+
23+
IWISH = words = "I wish I may I wish I might".split()
24+
25+
def test_trigrams_pairs():
26+
"""
27+
test that the build_trigram function creates the right pairs of words
28+
"""
29+
tris = trigrams.build_trigram(IWISH)
30+
31+
pairs = tris.keys()
32+
33+
# using a set here, as the dict_keys object is a set as well
34+
# And keys are always unique and hashable
35+
# and the order does not matter, so perfect for a set
36+
assert pairs == {("I", "wish"),
37+
("wish", "I"),
38+
("may", "I"),
39+
("I", "may"),
40+
}
41+
42+
43+
def test_trigrams_following_words():
44+
"""
45+
test that the following words are correct
46+
"""
47+
tris = trigrams.build_trigram(IWISH)
48+
49+
# this will only print if the test fails
50+
# but if if does, you can see what's going on to try to fix it.
51+
print(tris)
52+
53+
# a separate assert for each pair:
54+
assert tris[("I", "wish")] == ["I", "I"]
55+
assert tris[("wish", "I")] == ["may", "might"]
56+
assert tris[("may", "I")] == ["wish"]
57+
assert tris[("I", "may")] == ["I"]
58+
59+
60+
def test_pick_random_pair():
61+
test_pairs = {("one", "two"): [],
62+
("one", "three"): [],
63+
("four", "five"): [],
64+
("six", "seven"): [],
65+
("eight", "nine"): [],
66+
}
67+
# set the seed so we'll always get the same one
68+
random.seed(1234)
69+
pair = trigrams.pick_random_pair(test_pairs)
70+
71+
assert pair == ('six', 'seven')
72+
73+
74+

‎source/exercises/trigrams/trigrams.rst‎

Lines changed: 112 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ This produces an (ordered) list of words::
212212
213213
Now you've got some words to play with. Once you think you've got it working, try a bit longer piece of text. But this will do for now, and it's small and simple enough that you can immediately see if your code is working.
214214
215-
You will find that example in the test file, so we can write tests agains it:
215+
You will find that example in the test file, so we can write tests against it:
216216
217217
.. code-block:: python
218218
@@ -222,25 +222,27 @@ You will find that example in the test file, so we can write tests agains it:
222222
The trigrams structure
223223
----------------------
224224
225-
From above, this is what you need to build up something like this::
225+
Now we need to think a bit about what we want the trigrams structure to be.
226226
227-
"I wish" => ["I", "I"]
228-
"wish I" => ["may", "might"]
229-
"may I" => ["wish"]
230-
"I may" => ["I"]
227+
From above, we know that we need to build up something like this::
228+
229+
"I wish" => "I", "I"
230+
"wish I" => "may", "might"
231+
"may I" => "wish"
232+
"I may" => "I"
231233
232234
Hmmm, in a way, that's almost pseudo code. You have a bunch of word pairs, and for each word pair, there are one or more words that follow it.
233235
234-
Those following words look a lot like they are in a list, yes? Perfect, the list structure keeps order, and you can keep adding (appending) new words to it.
236+
Those following words look a lot like they could be in a list, yes? Perfect, the list structure keeps order, and you can keep adding (appending) new words to it.
235237
236-
Each of those lists of words needs to be mapped to a particular pair. Each pair is unique; it only shows up once (when that same pair is encountered again in the text, you add the follower to the list).
238+
Each of those lists of words needs to be mapped to a particular pair. Each pair is unique; it only shows up once (when that same pair is encountered again in the text, you add the follower to the list of following words).
237239
238240
That sounds a lot like a dictionary. The keys (word pairs) are unique, and map to a list of following words. (Note that, technically, in python the dictionary is only one implementation of a
239241
`Mapping <https://docs.python.org/3/glossary.html#term-mapping>`_.)
240242
241-
Now you have a choice of data structures: string or tuple.
243+
Now you have a choice of data structures for the word pairs, or keys in the dict: a string or a tuple.
242244
243-
String: The keys are a pair of words and can be represented as a string of two words with a space like so:
245+
**String**: The keys are a pair of words and can be represented as a string of two words with a space like so:
244246
245247
.. code-block:: python
246248
@@ -250,7 +252,7 @@ String: The keys are a pair of words and can be represented as a string of two w
250252
"I may": ["I"],
251253
}
252254
253-
Tuple: But strings are not the only type that you can use as keys in a dict; you can use any *immutable* type. Recall that tuples are immutable (they can't be changed once they have been created). Since each pair of words is, well, a pair, it makes sense to store each pair in a tuple, keeping the individual words separate:
255+
**Tuple**: But strings are not the only type that you can use as keys in a dictionary; you can use any *immutable* type. Recall that tuples are immutable (they can't be changed once they have been created). Since each pair of words is, well, a pair, it makes sense to store each pair in a tuple, keeping the individual words separate:
254256
255257
.. code-block:: python
256258
@@ -260,46 +262,44 @@ Tuple: But strings are not the only type that you can use as keys in a dict; you
260262
("I", "may"): ["I"],
261263
}
262264
263-
I like the example that uses tuples better, but either one will work.
265+
I like the version that uses tuples better, but either one will work. The test code is designed to check for word pairs in tuples. If you want to write your code using space separated strings, you can modify the tests.
264266
265267
Building the Trigrams dict
266268
..........................
267269
268270
So you've got a list of words, and you need to build up a dict like one of the above.
269271
270-
It's time to create a python file and start writting some code!
272+
It's time to create a python file and start writing some code!
273+
274+
Put this in your ``trigrams.py`` file
271275
272276
.. code-block:: python
273277
274278
#!/usr/bin/env python3
275279
276-
words = "I wish I may I wish I might".split()
277-
278-
279-
def build_trigrams(words):
280+
def build_trigram(words):
280281
"""
281282
build up the trigrams dict from the list of words
282283
283-
returns a dict with:
284-
keys: word pairs
285-
values: list of followers
284+
:param words: a list of individual words in order
285+
286+
:returns: a dict with:
287+
keys: word pairs in tuples
288+
values: list of the words that follow the pain in the key
286289
"""
290+
287291
trigrams = {}
288292
289293
# build up the dict here!
290294
291295
return trigrams
292296
293297
294-
if __name__ == "__main__":
295-
trigrams = build_trigrams(words)
296-
print(trigrams)
297-
298298
So how do you actually build up that dict? That's kind of the point of the exercise, so I won't tell you that ... but here are some hints:
299299
300300
**Looping through the words**
301301
302-
Obviously you need to loop through all the words, so a ``for`` loop makes sense. However, this is a bit tricky. Usually in Python you loop through all the items in a list, and don't worry about the indices:
302+
Obviously you need to loop through all the words, so a ``for`` loop makes sense. However, this is a bit tricky. Usually in Python you loop through all the items in a list, and don't worry about the indexes:
303303
304304
.. code-block:: python
305305
@@ -331,18 +331,69 @@ For each pair in the text, you need to add it to the dict. But:
331331
332332
("wish", "I"): ["may", "might"]
333333
334-
Note that the example above suggests the basic logic; it's almost pseudo-code. And that logic will work. But it turns out that this is a common enough operation that python dicts have a method that lets you do that logic in one step? Can you find it?
334+
Note that the description above suggests the basic logic; it's almost pseudo-code. And that logic will work. But it turns out that this is a common enough operation that python dicts have a method that lets you do that logic in one step? Can you find it?
335335
336336
`Python dict Documentation <https://docs.python.org/3/library/stdtypes.html?highlight=dictionary#mapping-types-dict>`_
337337
338-
You should now have code that will return a dict like we noted above::
338+
As you develop this code, run the tests each time you think you have made some progress::
339+
340+
$ pytest test_trigrams.py
341+
342+
In that test file, there are two tests of the `trigrams()` function: One that tests that it gets the right word pairs as keys:
343+
344+
.. code-block:: python
345+
346+
def test_trigrams_pairs():
347+
"""
348+
test that the build_trigram function creates the right pairs of words
349+
"""
350+
tris = trigrams.build_trigram(IWISH)
351+
352+
pairs = tris.keys()
353+
354+
# using a set here, as the dict_keys object is a set as well
355+
# And keys are always unique and hashable
356+
# and the order does not matter, so perfect for a set
357+
assert pairs == {("I", "wish"),
358+
("wish", "I"),
359+
("may", "I"),
360+
("I", "may"),
361+
}
362+
363+
and one that tests if the following word lists are correct:
364+
365+
.. code-block:: python
366+
367+
def test_trigrams_following_words():
368+
"""
369+
test that the following words are correct
370+
"""
371+
tris = trigrams.build_trigram(IWISH)
372+
373+
# this will only print if the test fails
374+
# but if if does, you can see what's going on to try to fix it.
375+
print(tris)
376+
377+
# a separate assert for each pair:
378+
assert tris[("I", "wish")] == ["I", "I"]
379+
assert tris[("wish", "I")] == ["may", "might"]
380+
assert tris[("may", "I")] == ["wish"]
381+
assert tris[("I", "may")] == ["I"]
382+
383+
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!
384+
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:
386+
`Write Explicit Tests <https://amir.rachum.com/blog/2017/01/14/explicit-tests/>`_
387+
388+
If both tests pass, you should now have code that will return a dict like we noted above::
339389
340390
{("I", "wish"): ["I", "I"],
341391
("wish", "I"): ["may", "might"],
342392
("may", "I"): ["wish"],
343393
("I", "may"): ["I"]}
344394
345-
Try it out on a longer bit of text (your choice) before you go any further.
395+
Try it out on a longer bit of text (your choice) before you go any further. If it doesn't work correctly, make sure to write a test that catches the problem before you fix it!
396+
346397
347398
Using the Trigrams dict
348399
.......................
@@ -361,18 +412,49 @@ This is the fun part. Once you have a mapping of word pairs to following words,
361412
# pick a random item from a sequence
362413
random.choice(a_list)
363414
364-
- You need to start with the first word pair; picking a random key from a dict is actually a bit tricky. Start with this known pair, and once you have the code working, you can figure out a better way to pick a pair to start with.
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. We show a bit of both in the provided tests.
416+
417+
Tactic one is to break you code down into pieces that you *can* test -- everything BUT the random choices.
418+
419+
Tactic two is to take advantage of the random "`seed <https://en.wikipedia.org/wiki/Random_seed>`_". 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. But if you start with the same initial value, known as the "seed", then you will get the same sequence of numbers. We can take advantage of this in our tests, as the built in ``random`` module provides a way to `set the seed <https://docs.python.org/3/library/random.html#random.seed>`_
420+
421+
The provided tests use a both of these tactics.
422+
423+
- You need to start with the first word pair; picking a random key from a dict is actually a bit tricky. But we have a test for it:
424+
425+
.. code-block:: python
426+
427+
def test_pick_random_pair():
428+
test_pairs = {("one", "two"): [],
429+
("one", "three"): [],
430+
("four", "five"): [],
431+
("six", "seven"): [],
432+
("eight", "nine"): [],
433+
}
434+
# set the seed so we'll always get the same one
435+
random.seed(1234)
436+
pair = trigrams.pick_random_pair(test_pairs)
437+
438+
assert pair == ('six', 'seven')
439+
440+
So you'll need to define a function: ``pick_random_pair()`` that takes your trigram dict as input, and returns a random key.
441+
442+
Note that that particular result 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.
443+
365444
366445
- As you build up your text, 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)``
367446
368447
- Remember that after adding a word to a pair to make a three-word text, the next pair is the last two words in that three-word text.
369448
370-
- What to do if you end up with a word pair that isn't in the original text?
449+
- What to do if you end up with a word pair that isn't in the original text? It's unlikely on a long text, but possible.
371450
372451
- How to terminate? Probably have a pre-defined length of text!
373452
453+
454+
374455
Once you have the basics working, try your code on a longer piece of input text. Then think about making it fancy. Can you make sentences with capitalized first words and punctuation? Anything else to make the text more "real"?
375456
457+
376458
Processing the Input Text
377459
-------------------------
378460

0 commit comments

Comments
 (0)