Think Python/Case study: word play

Reading word lists
For the exercises in this chapter we need a list of English words. There are lots of word lists available on the Web, but the one most suitable for our purpose is one of the word lists collected and contributed to the public domain by Grady Ward as part of the Moby lexicon project. It is a list of 113,809 official crosswords; that is, words that are considered valid in crossword puzzles and other word games. In the Moby collection, the filename is 113809of.fic; I include a copy of this file, with the simpler name words.txt, along with Swampy.

This file is in plain text, so you can open it with a text editor, but you can also read it from Python. (You may need to move the file from the swampy folder into the main python folder) The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file.

fin is a common name for a file object used for input. Mode  indicates that this file is open for reading (as opposed to  for writing).

The file object provides several methods for reading, including readline, which reads characters from the file until it gets to a newline and returns the result as a string: The first word in this particular list is &#X201C;aa,&#X201D; which is a kind of lava. The sequence  represents two whitespace characters, a carriage return and a newline, that separate this word from the next.

The file object keeps track of where it is in the file, so if you call readline again, you get the next word: The next word is &#X201C;aah,&#X201D; which is a perfectly legitimate word, so stop looking at me like that. Or, if it&#X2019;s the whitespace that&#X2019;s bothering you, we can get rid of it with the string method strip:

You can also use a file object as part of a for loop. This program reads <TT>words.txt</TT> and prints each word, one per line:

<DIV CLASS="theorem">Exercise&#XA0;1&#XA0;&#XA0; Write a program that reads '<TT>words.txt</TT>' and prints only the words with more than 20 characters (not counting whitespace). </DIV>

Exercises
There are solutions to these exercises in the next section. You should at least attempt each one before you read the solutions.

<DIV CLASS="theorem">Exercise&#XA0;2&#XA0;&#XA0; In 1939 Ernest Vincent Wright published a 50,000 word novel called Gadsby that does not contain the letter &#X201C;e.&#X201D; Since &#X201C;e&#X201D; is the most common letter in English, that&#X2019;s not easy to do.

''In fact, it is difficult to construct a solitary thought without using that most common symbol. It is slow going at first, but with caution and hours of training you can gradually gain facility.''

All right, I&#X2019;ll stop now.

Write a function called   that returns '<TT>True</TT>' if the given word doesn&#X2019;t have the letter &#X201C;e&#X201D; in it.

Modify your program from the previous section to print only the words that have no &#X201C;e&#X201D; and compute the percentage of the words in the list have no &#X201C;e.&#X201D; </DIV>

<DIV CLASS="theorem">Exercise&#XA0;3&#XA0;&#XA0; Write a function named '<TT>avoids</TT>' that takes a word and a string of forbidden letters, and that returns '<TT>True</TT>' if the word doesn&#X2019;t use any of the forbidden letters.

''Modify your program to prompt the user to enter a string of forbidden letters and then print the number of words that don&#X2019;t contain any of them. Can you find a combination of 5 forbidden letters that excludes the smallest number of words?'' </DIV>

<DIV CLASS="theorem">Exercise&#XA0;4&#XA0;&#XA0; Write a function named  '' that takes a word and a string of letters, and that returns '<TT>True</TT>' if the word contains only letters in the list. Can you make a sentence using only the letters '<TT>acefhlo</TT>'? Other than &#X201C;Hoe alfalfa?&#X201D;''</DIV>

<DIV CLASS="theorem">Exercise&#XA0;5&#XA0;&#XA0;  Write a function named  '' that takes a word and a string of required letters, and that returns '<TT>True</TT>' if the word uses all the required letters at least once. How many words are there that use all the vowels '<TT>aeiou</TT>'? How about '<TT>aeiouy</TT>'?''</DIV>

<DIV CLASS="theorem">Exercise&#XA0;6&#XA0;&#XA0; Write a function called  '' that returns '<TT>True</TT>' if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there?''</DIV>

Search
All of the exercises in the previous section have something in common; they can be solved with the search pattern we saw in Section&#XA0;8.6. The simplest example is: The <TT>for</TT> loop traverses the characters in <TT>word</TT>. If we find the letter &#X201C;e&#X201D;, we can immediately return <TT>False</TT>; otherwise we have to go to the next letter. If we exit the loop normally, that means we didn&#X2019;t find an &#X201C;e&#X201D;, so we return <TT>True</TT>.

You can write this function more concisely using the <TT>in</TT> operator, but I started with this version because it demonstrates the logic of the search pattern.

<TT>avoids</TT> is a more general version of  but it has the same structure: We can return <TT>False</TT> as soon as we find a forbidden letter; if we get to the end of the loop, we return <TT>True</TT>.

is similar except that the sense of the condition is reversed: Instead of a list of forbidden words, we have a list of available words. If we find a letter in <TT>word</TT> that is not in <TT>available</TT>, we can return <TT>False</TT>.

is similar except that we reverse the role of the word and the string of letters:

Instead of traversing the letters in <TT>word</TT>, the loop traverses the required letters. If any of the required letters do not appear in the word, we can return <TT>False</TT>.

If you were really thinking like a computer scientist, you would have recognized that  was an instance of a previously-solved problem, and you would have written:

This is an example of a program development method called problem recognition, which means that you recognize the problem you are working on as an instance of a previously-solved problem, and apply a previously-developed solution.

Looping with indices
I wrote the functions in the previous section with <TT>for</TT> loops because I only needed the characters in the strings; I didn&#X2019;t have to do anything with the indices.

For  we have to compare adjacent letters, which is a little tricky with a <TT>for</TT> loop: An alternative is to use recursion: Another option is to use a <TT>while</TT> loop: The loop starts at <TT>i=0</TT> and ends when <TT>i=len(word)-1</TT>. Each time through the loop, it compares the <I>i</I>th character (which you can think of as the current character) to the <I>i</I>+1th character (which you can think of as the next).

If the next character is less than (alphabetically before) the current one, then we have discovered a break in the abecedarian trend, and we return <TT>False</TT>.

If we get to the end of the loop without finding a fault, then the word passes the test. To convince yourself that the loop ends correctly, consider an example like. The length of the word is 6, so the last time the loop runs is when <TT>i</TT> is 4, which is the index of the second-to-last character. On the last iteration, it compares the second-to-last character to the last, which is what we want.

Here is a version of  (see Exercise&#XA0;6.6) that uses two indices; one starts at the beginning and goes up; the other starts at the end and goes down. Or, if you noticed that this is an instance of a previously-solved problem, you might have written:

Assuming you did Exercise&#XA0;8.8.

Debugging
Testing programs is hard. The functions in this chapter are relatively easy to test because you can check the results by hand. Even so, it is somewhere between difficult and impossible to choose a set of words that test for all possible errors.

Taking  as an example, there are two obvious cases to check: words that have an &#X2019;e&#X2019; should return <TT>False</TT>; words that don&#X2019;t should return <TT>True</TT>. You should have no trouble coming up with one of each.

Within each case, there are some less obvious subcases. Among the words that have an &#X201C;e,&#X201D; you should test words with an &#X201C;e&#X201D; at the beginning, the end, and somewhere in the middle. You should test long words, short words, and very short words, like the empty string. The empty string is an example of a special case, which is one of the non-obvious cases where errors often lurk.

In addition to the test cases you generate, you can also test your program with a word list like <TT>words.txt</TT>. By scanning the output, you might be able to catch errors, but be careful: you might catch one kind of error (words that should not be included, but are) and not another (words that should be included, but aren&#X2019;t).

In general, testing can help you find bugs, but it is not easy to generate a good set of test cases, and even if you do, you can&#X2019;t be sure your program is correct.

According to a legendary computer scientist: <BLOCKQUOTE CLASS="quote"> Program testing can be used to show the presence of bugs, but never to show their absence! &#X2014; Edsger W. Dijkstra

</BLOCKQUOTE>

Glossary
<DL CLASS="description"><DT CLASS="dt-description">file object:</DT><DD CLASS="dd-description"> A value that represents an open file.

</DD><DT CLASS="dt-description">problem recognition:</DT><DD CLASS="dd-description"> A way of solving a problem by expressing it as an instance of a previously-solved problem. </DD><DT CLASS="dt-description">special case:</DT><DD CLASS="dd-description"> A test case that is atypical or non-obvious (and less likely to be handled correctly). </DD></DL>

Exercise 7
This question is based on a Puzzler that was broadcast on the radio program Car Talk :

<BLOCKQUOTE CLASS="quote">Give me a word with three consecutive double letters. I'll give you a couple of words that almost qualify, but don't. For example, the word committee, c-o-m-m-i-t-t-e-e. It would be great except for the &#X2018;i&#X2019; that sneaks in there. Or Mississippi: M-i-s-s-i-s-s-i-p-p-i. If you could take out those i&#X2019;s it would work. But there is a word that has three consecutive pairs of letters and to the best of my knowledge this may be the only word. Of course there are probably 500 more but I can only think of one. What is the word? </BLOCKQUOTE>

''Write a program to find it. You can see my solution at '<TT>thinkpython.com/code/cartalk.py</TT>'.''

Exercise 8
Here&#X2019;s another Car Talk Puzzler : <BLOCKQUOTE CLASS="quote"> ''&#X201C;I was driving on the highway the other day and I happened to notice my odometer. Like most odometers, it shows six digits, in whole miles only. So, if my car had 300,000 miles, for example, I&#X2019;d see 3-0-0-0-0-0.''

''&#X201C;Now, what I saw that day was very interesting. I noticed that the last 4 digits were palindromic; that is, they read the same forward as backward. For example, 5-4-4-5 is a palindrome, so my odometer could have read 3-1-5-4-4-5.''

''&#X201C;One mile later, the last 5 numbers were palindromic. For example, it could have read 3-6-5-4-5-6. One mile after that, the middle 4 out of 6 numbers were palindromic. And you ready for this? One mile later, all 6 were palindromic!''

&#X201C;The question is, what was on the odometer when I first looked?&#X201D; </BLOCKQUOTE>

''Write a Python program that tests all the six-digit numbers and prints any numbers that satisfy these requirements. You can see my solution at '<TT>thinkpython.com/code/cartalk.py</TT>'.''

Exercise 9
Here&#X2019;s another Car Talk Puzzler you can solve with a search :

<BLOCKQUOTE CLASS="quote"> ''&#X201C;Recently I had a visit with my mom and we realized that the two digits that make up my age when reversed resulted in her age. For example, if she&#X2019;s 73, I&#X2019;m 37. We wondered how often this has happened over the years but we got sidetracked with other topics and we never came up with an answer.''

''&#X201C;When I got home I figured out that the digits of our ages have been reversible six times so far. I also figured out that if we&#X2019;re lucky it would happen again in a few years, and if we&#X2019;re really lucky it would happen one more time after that. In other words, it would have happened 8 times over all. So the question is, how old am I now?&#X201D;'' </BLOCKQUOTE> ''Write a Python program that searches for solutions to this Puzzler. Hint: you might find the string method '<TT>zfill</TT>' useful.''

You can see my solution at '<TT>thinkpython.com/code/cartalk.py</TT>'.