Archive:Think Python/Case study: data structure selection
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML> <HEAD>
<META http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <META name="GENERATOR" content="hevea 1.10"> <LINK rel="stylesheet" type="text/css" href="book.css"> <TITLE>Case study: data structure selection</TITLE> </HEAD> <BODY > <A HREF="book013.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="book015.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
<A NAME="htoc155">Chapter 13</A> Case study: data structure selection
<A NAME="toc141"></A><A NAME="htoc156">13.1</A> Word frequency analysis
<A NAME="analysis"></A>
As usual, you should at least attempt the following exercises before you read my solutions.
Write a program that reads a file, breaks each line into words, strips whitespace and punctuation from the words, and
converts them to lowercase.<A NAME="@default1158"></A> <A NAME="@default1159"></A>
Hint: The string module provides strings named whitespace,
which contains space, tab, newline, etc., and punctuation which contains the punctuation characters. Let’s see
if we can make Python swear:<EM><FONT COLOR=blue><FONT SIZE=4>>>> import string
>>> print string.punctuation
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
</FONT></FONT></EM>Also, you might consider using the string methods strip, replace and translate.
<A NAME="@default1160"></A>
<A NAME="@default1161"></A> <A NAME="@default1162"></A> <A NAME="@default1163"></A> <A NAME="@default1164"></A>
<A NAME="@default1165"></A><A NAME="@default1166"></A>
Go to Project Gutenberg (gutenberg.net) and download your favorite out-of-copyright book in plain text format.
<A NAME="@default1167"></A> <A NAME="@default1168"></A>
Modify your program from the previous exercise to read the book
you downloaded, skip over the header information at the beginning
of the file, and process the rest of the words as before.Then modify the program to count the total number of words in the book, and the number of times each word is used.
<A NAME="@default1169"></A> <A NAME="@default1170"></A>
Print the number of different words used in the book. Compare
different books by different authors, written in different eras. Which author uses the most extensive vocabulary?
Modify the program from the previous exercise to print the 20 most frequently-used words in the book.
Modify the previous program to read a word list (see Section <A HREF="book010.html#wordlist">9.1</A>) and then print all the words in the book that are not in the word list. How many of them are typos? How many of them are common words that should be in the word list, and how many of them are really obscure?
<A NAME="toc142"></A><A NAME="htoc157">13.2</A> Random numbers
<A NAME="@default1171"></A>
<A NAME="@default1172"></A> <A NAME="@default1173"></A>
<A NAME="@default1174"></A>
Given the same inputs, most computer programs generate the same
outputs every time, so they are said to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. Games are an obvious
example, but there are more.
Making a program truly nondeterministic turns out to be not so easy,
but there are ways to make it at least seem nondeterministic. One of them is to use algorithms that generate pseudorandom numbers. Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it
is all but impossible to distinguish them from random.
<A NAME="@default1175"></A> <A NAME="@default1176"></A>
The random module provides functions that generate
pseudorandom numbers (which I will simply call “random” from
here on).
<A NAME="@default1177"></A> <A NAME="@default1178"></A>
The function random returns a random float
between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you call random, you get the next number in a long series. To see a
sample, run this loop:
<FONT COLOR=blue><FONT SIZE=4>import random
for i in range(10):
x = random.random()
print x
</FONT></FONT>The function randint takes parameters low and
high and returns an integer between low and
high (including both).
<A NAME="@default1179"></A> <A NAME="@default1180"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> random.randint(5, 10) 5 >>> random.randint(5, 10) 9 </FONT></FONT>
To choose an element from a sequence at random, you can use choice:
<A NAME="@default1181"></A> <A NAME="@default1182"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> t = [1, 2, 3] >>> random.choice(t) 2 >>> random.choice(t) 3 </FONT></FONT>
The random module also provides functions to generate
random values from continuous distributions including
Gaussian, exponential, gamma, and a few more.
<A NAME="@default1183"></A>
Write a function named choose_from_hist that takes
a histogram as defined in Section <A HREF="book012.html#histogram">11.1</A> and returns a random value from the histogram, chosen with probability
in proportion to frequency. For example, for this histogram:<EM><FONT COLOR=blue><FONT SIZE=4>>>> t = ['a', 'a', 'b']
>>> h = histogram(t)
>>> print h
{'a': 2, 'b': 1}
</FONT></FONT></EM>your function should ’a’ with probability 2/3 and 'b'
with probability 1/3.
<A NAME="toc143"></A><A NAME="htoc158">13.3</A> Word histogram
Here is a program that reads a file and builds a histogram of the words in the file:
<A NAME="@default1184"></A>
<FONT COLOR=blue><FONT SIZE=4>import string
def process_file(filename):
h = dict()
fp = open(filename)
for line in fp:
process_line(line, h)
return h
def process_line(line, h):
line = line.replace('-', ' ')
for word in line.split():
word = word.strip(string.punctuation + string.whitespace)
word = word.lower()
h[word] = h.get(word, 0) + 1
hist = process_file('emma.txt')
</FONT></FONT>This program reads emma.txt, which contains the text of Emma by Jane Austen.
<A NAME="@default1185"></A>
process_file loops through the lines of the file,
passing them one at a time to process_line. The histogram
h is being used as an accumulator.
<A NAME="@default1186"></A> <A NAME="@default1187"></A>
process_line uses the string method replace to replace
hyphens with spaces before using split to break the line into a list of strings. It traverses the list of words and uses strip and lower to remove punctuation and convert to lower case. (It is a shorthand to say that strings are “converted;” remember that string are immutable, so methods like strip and lower
return new strings.)
Finally, process_line updates the histogram by creating a new
item or incrementing an existing one.
<A NAME="@default1188"></A>
To count the total number of words in the file, we can add up the frequencies in the histogram:
<FONT COLOR=blue><FONT SIZE=4>def total_words(h):
return sum(h.values())
</FONT></FONT>The number of different words is just the number of items in the dictionary:
<FONT COLOR=blue><FONT SIZE=4>def different_words(h):
return len(h)
</FONT></FONT>Here is some code to print the results:
<FONT COLOR=blue><FONT SIZE=4>print 'Total number of words:', total_words(hist)print 'Number of different words:', different_words(hist)
</FONT></FONT>
And the results:
<FONT COLOR=blue><FONT SIZE=4>Total number of words: 161073Number of different words: 7212
</FONT></FONT>
<A NAME="toc144"></A><A NAME="htoc159">13.4</A> Most common words
<A NAME="@default1189"></A> <A NAME="@default1190"></A>
To find the most common words, we can apply the DSU pattern;
most_common takes a histogram and returns a list of
word-frequency tuples, sorted in reverse order by frequency:
<FONT COLOR=blue><FONT SIZE=4>def most_common(h):
t = []
for key, value in h.items():
t.append((value, key))
t.sort(reverse=True)
return t
</FONT></FONT>Here is a loop that prints the ten most common words:
<FONT COLOR=blue><FONT SIZE=4>t = most_common(hist)print 'The most common words are:' for freq, word in t[0:10]:
print word, '\t', freq</FONT></FONT>
And here are the results from Emma:
<FONT COLOR=blue><FONT SIZE=4>The most common words are:to 5242 the 5204 and 4897 of 4293 i 3191 a 3130 it 2529 her 2483 was 2400 she 2364
</FONT></FONT>
<A NAME="toc145"></A><A NAME="htoc160">13.5</A> Optional parameters
<A NAME="@default1191"></A> <A NAME="@default1192"></A>
We have seen built-in functions and methods that take a variable
number of arguments. It is possible to write user-defined functions with optional arguments, too. For example, here is a function that
prints the most common words in a histogram
<FONT COLOR=blue><FONT SIZE=4>def print_most_common(hist, num=10)
t = most_common(hist)
print 'The most common words are:'
for freq, word in t[0:num]:
print word, '\t', freq
</FONT></FONT>The first parameter is required; the second is optional. The default value of num is 10.
<A NAME="@default1193"></A> <A NAME="@default1194"></A>
If you only provide one argument:
<FONT COLOR=blue><FONT SIZE=4>print_most_common(hist) </FONT></FONT>
num gets the default value. If you provide two arguments:
<FONT COLOR=blue><FONT SIZE=4>print_most_common(hist, 20) </FONT></FONT>
num gets the value of the argument instead. In other words, the optional argument overrides the default value.
<A NAME="@default1195"></A>
If a function has both required and optional parameters, all
the required parameters have to come first, followed by the
optional ones.
<A NAME="toc146"></A><A NAME="htoc161">13.6</A> Dictionary subtraction
<A NAME="@default1196"></A> <A NAME="@default1197"></A>
Finding the words from the book that are not in the word list
from words.txt is a problem you might recognize as set subtraction; that is, we want to find all the words from one set (the words in the book) that are not in another set (the
words in the list).
subtract takes dictionaries d1 and d2 and returns a
new dictionary that contains all the keys from d1 that are not in d2. Since we don’t really care about the values, we
set them all to None.
<FONT COLOR=blue><FONT SIZE=4>def subtract(d1, d2):
res = dict()
for key in d1:
if key not in d2:
res[key] = None
return res
</FONT></FONT>To find the words in the book that are not in words.txt,
we can use process_file to build a histogram for
words.txt, and then subtract:
<FONT COLOR=blue><FONT SIZE=4>words = process_file('words.txt')
diff = subtract(hist, words)
print "The words in the book that aren't in the word list are:"
for word in diff.keys():
print word,
</FONT></FONT>Here are some of the results from Emma:
<FONT COLOR=blue><FONT SIZE=4>The words in the book that aren't in the word list are:rencontre jane's blanche woodhouses disingenuousnessfriend's venice apartment ...
</FONT></FONT>
Some of these words are names and possessives. Others, like
“rencontre,” are no longer in common use. But a few are common
words that should really be in the list!
<A NAME="@default1198"></A> <A NAME="@default1199"></A>
Python provides a data structure called set that provides many
common set operations. Read the documentation at docs.python.org/lib/types-set.html and write a program that uses set subtraction to find words in the book that are not in the word list.
<A NAME="toc147"></A><A NAME="htoc162">13.7</A> Random words
<A NAME="randomwords"></A>
<A NAME="@default1200"></A>
To choose a random word from the histogram, the simplest algorithm
is to build a list with multiple copies of each word, according
to the observed frequency, and then choose from the list:
<FONT COLOR=blue><FONT SIZE=4>def random_word(h):
t = []
for word, freq in h.items():
t.extend([word] * freq)
return random.choice(t)
</FONT></FONT>The expression [word] * freq creates a list with freq
copies of the string word. The extend method is similar to append except that the argument is
a sequence.
<A NAME="@default1201"></A>
This algorithm works, but it is not very efficient; each time you
choose a random word, it rebuilds the list, which is as big as the original book. An obvious improvement is to build the list
once and then make multiple selections, but the list is still big.An alternative is:
- Use keys to get a list of the words in the book.
- Build a list that contains the cumulative sum of the word
frequencies (see Exercise <A HREF="book011.html#cumulative">10.1</A>). The last item
in this list is the total number of words in the book, n. - Choose a random number from 1 to n. Use a bisection search (See Exercise <A HREF="book011.html#bisection">10.8</A>) to find the index where the random number would be inserted in the cumulative sum.
- Use the index to find the corresponding word in the word list.
Write a program that uses this algorithm to choose a random
word from the book.
<A NAME="toc148"></A><A NAME="htoc163">13.8</A> Markov analysis
<A NAME="@default1202"></A>
If you choose words from the book at random, you can get a sense of the vocabulary, you probably won’t get a sentence:
<FONT COLOR=blue><FONT SIZE=4>this the small regard harriet which knightley's it most things </FONT></FONT>
A series of random words seldom makes sense because there
is no relationship between successive words. For example, in a real sentence you would expect an article like “the” to be followed by an adjective or a noun, and probably not a verb
or adverb.
One way to measure these kinds of relationships is Markov
analysis, which characterizes, for a given sequence of words, the probability of the word that comes next. For example,
the song Eric, the Half a Bee begins:
Half a bee, philosophically,
Must, ipso facto, half not be.
But half the bee has got to be
Vis a vis, its entity. D’you see?
But can a bee be said to be
Or not to be an entire bee
When half the bee is not a bee
Due to some ancient injury?
In this text, the phrase “half the” is always followed by the word “bee,” but the phrase “the bee” might be followed by either
“has” or “is”.
<A NAME="@default1203"></A>
<A NAME="@default1204"></A>
<A NAME="@default1205"></A>
The result of Markov analysis is a mapping from each prefix
(like “half the” and “the bee”) to all possible suffixes
(like “has” and “is”).
<A NAME="@default1206"></A> <A NAME="@default1207"></A>
Given this mapping, you can generate a random text by
starting with any prefix and choosing at random from the possible suffixes. Next, you can combine the end of the
prefix and the new suffix to form the next prefix, and repeat.
For example, if you start with the prefix “Half a,” then the
next word has to be “bee,” because the prefix only appears once in the text. The next prefix is “a bee,” so the
next suffix might be “philosophically,” “be” or “due.”
In this example the length of the prefix is always two, but
you can do Markov analysis with any prefix length. The length
of the prefix is called the “order” of the analysis.
- Write a program to read a text from a file and perform Markov analysis. The result should be a dictionary that maps from prefixes to a collection of possible suffixes. The collection might be a list, tuple, or dictionary; it is up to you to make an appropriate choice. You can test your program with prefix length two, but you should write the program in a way that makes it easy to try other lengths.
- Add a function to the previous program to generate random text
based on the Markov analysis. Here is an example from Emma
with prefix length 2:
He was very clever, be it sweetness or be angry, ashamed or only amused, at such a stroke. She had never thought of Hannah till you were never meant for me?" "I cannot make speeches, Emma:" he soon cut it all himself.
For this example, I left the punctuation attached to the words.
The result is almost syntactically correct, but not quite.
Semantically, it almost makes sense, but not quite.What happens if you increase the prefix length? Does the random text make more sense?
<A NAME="@default1208"></A>
- Once your program is working, you might want to try a mash-up:
if you analyze text from two or more books, the random text you generate will blend the vocabulary and phrases from
the sources in interesting ways.
<A NAME="toc149"></A><A NAME="htoc164">13.9</A> Data structures
<A NAME="@default1209"></A>
Using Markov analysis to generate random text is fun, but there is
also a point to this exercise: data structure selection. In your
solution to the previous exercises, you had to choose:
- How to represent the prefixes.
- How to represent the collection of possible suffixes.
- How to represent the mapping from each prefix to the collection of possible suffixes.
Ok, the last one is the easy; the only mapping type we have seen is a dictionary, so it is the natural choice.
For the prefixes, the most obvious options are string,
list of strings, or tuple of strings. For the suffixes,
one option is a list; another is a histogram (dictionary).
<A NAME="@default1210"></A>
How should you choose? The first step is to think about
the operations you will need to implement for each data structure. For the prefixes, we need to be able to remove words from the beginning and add to the end. For example, if the current prefix is “Half a,” and the next word is “bee,” you need
to be able to form the next prefix, “a bee.”
<A NAME="@default1211"></A>
Your first choice might be a list, since it is easy to add
and remove elements, but we also need to be able to use the prefixes as keys in a dictionary, so that rules out lists. With tuples, you can’t append or remove, but you can use
the addition operator to form a new tuple:
<FONT COLOR=blue><FONT SIZE=4>def shift(prefix, word):
return prefix[1:] + (word,)
</FONT></FONT>shift takes a tuple of words, prefix, and a string,
word, and forms a new tuple that has all the words in prefix except the first, and word added to
the end.
For the collection of suffixes, the operations we need to
perform include adding a new suffix (or increasing the frequency
of an existing one), and choosing a random suffix.
Adding a new suffix is equally easy for the list implementation
or the histogram. Choosing a random element from a list is easy; choosing from a histogram is harder to do
efficiently (see Exercise <A HREF="#randhist">13.7</A>).
So far we have been talking mostly about ease of implementation,
but there are other factors to consider in choosing data structures. One is run time. Sometimes there is a theoretical reason to expect one data structure to be faster than other; for example, I mentioned that the in operator is faster for dictionaries than for lists,
at least when the number of elements is large.
But often you don’t know ahead of time which implementation will
be faster. One option is to implement both of them and see which is better. This approach is called benchmarking. A practical alternative is to choose the data structure that is easiest to implement, and then see if it is fast enough for the intended application. If so, there is no need to go on. If not, there are tools, like the profile module, that can identify
the places in a program that take the most time.
<A NAME="@default1212"></A>
<A NAME="@default1213"></A>
<A NAME="@default1214"></A>
The other factor to consider is storage space. For example, using a
histogram for the collection of suffixes might take less space because you only have to store each word once, no matter how many times it appears in the text. In some cases, saving space can also make your program run faster, and in the extreme, your program might not run at all if you run out of memory. But for many applications, space is a
secondary consideration after run time.
One final thought: in this discussion, I have implied that
we should use one data structure for both analysis and generation. But since these are separate phases, it would also be possible to use one structure for analysis and then convert to another structure for generation. This would be a net win if the time saved during
generation exceeded the time spent in conversion.
<A NAME="toc150"></A><A NAME="htoc165">13.10</A> Debugging
<A NAME="@default1215"></A>
When you are debugging a program, and especially if you are working on a hard bug, there are four things to try:
- reading:
- Examine your code, read it back to yourself, and check that it says what you meant to say.
- running:
- Experiment by making changes and running different versions. Often if you display the right thing at the right place in the program, the problem becomes obvious, but sometimes you have to spend some time to build scaffolding.
- ruminating:
- Take some time to think! What kind of error is it: syntax, runtime, semantic? What information can you get from the error messages, or from the output of the program? What kind of error could cause the problem you’re seeing? What did you change last, before the problem appeared?
- retreating:
- At some point, the best thing to do is back off, undoing recent changes, until you get back to a program that works and that you understand. Then you can starting rebuilding.
Beginning programmers sometimes get stuck on one of these activities
and forget the others. Each activity comes with its own failure
mode.
<A NAME="@default1216"></A>
For example, reading your code might help if the problem is a
typographical error, but not if the problem is a conceptual misunderstanding. If you don’t understand what your program does, you can read it 100 times and never see the error, because the error is in
your head.
<A NAME="@default1217"></A>
Running experiments can help, especially if you run small, simple
tests. But if you run experiments without thinking or reading your code, you might fall into a pattern I call “random walk programming,” which is the process of making random changes until the program does the right thing. Needless to say, random walk programming
can take a long time.
<A NAME="@default1218"></A> <A NAME="@default1219"></A>
You have to take time to think. Debugging is like an
experimental science. You should have at least one hypothesis about what the problem is. If there are two or more possibilities, try to
think of a test that would eliminate one of them.
Taking a break helps with the thinking. So does talking.
If you explain the problem to someone else (or even yourself), you
will sometimes find the answer before you finish asking the question.
But even the best debugging techniques will fail if there are too many
errors, or if the code you are trying to fix is too big and complicated. Sometimes the best option is to retreat, simplifying the program until you get to something that works and that you
understand.
Beginning programmers are often reluctant to retreat because
they can’t stand to delete a line of code (even if it’s wrong). If it makes you feel better, copy your program into another file before you start stripping it down. Then you can paste the pieces
back in a little bit at a time.
Finding a hard bug requires reading, running, ruminating, and
sometimes retreating. If you get stuck on one of these activities,
try the others.
<A NAME="toc151"></A><A NAME="htoc166">13.11</A> Glossary
- deterministic:
- Pertaining to a program that does the same
thing each time it runs, given the same inputs.
<A NAME="@default1220"></A> - pseudorandom:
- Pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program. <A NAME="@default1221"></A>
- default value:
- The value given to an optional parameter if no argument is provided. <A NAME="@default1222"></A>
- override:
- To replace a default value with an argument. <A NAME="@default1223"></A>
- benchmarking:
- The process of choosing between data structures by implementing alternatives and testing them on a sample of the possible inputs. <A NAME="@default1224"></A>
<A NAME="toc152"></A><A NAME="htoc167">13.12</A> Exercises
<A NAME="@default1225"></A>
<A NAME="@default1226"></A>
<A NAME="@default1227"></A>The “rank” of a word is its position in a list of words
sorted by frequency: the most common word has rank 1, the
second most common has rank 2, etc.Zipf’s law describes a relationship between the ranks and frequencies
of words in natural languages<A NAME="text29" HREF="#note29">1</A>. Specifically, it
predicts that the frequency, f, of the word with rank r is:| f = c r−s |
where s and c are parameters that depend on the language and the text. If you take the logarithm of both sides of this equation, you
get:<A NAME="@default1228"></A>
| logf = logc − s logr |
So if you plot logf versus logr, you should get
a straight line with slope −s and intercept logc.Write a program that reads a text from a file, counts
word frequencies, and prints one line for each word, in descending order of frequency, with logf and logr. Use the graphing program of your choice to plot the results and check whether they form a straight line. Can you estimate the value of s?
- <A NAME="note29" HREF="#text29">1</A>
- See wikipedia.org/wiki/Zipf's_law
<A HREF="book013.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="book015.html"><IMG SRC="next_motif.gif" ALT="Next"></A> </BODY> </HTML>