Think Python How to Think Like a Computer Scientist
Download 1.04 Mb. Pdf ko'rish
|
thinkpython
- Bu sahifa navigatsiya:
- Exercise 13.2
12.11. Exercises
125 Write a program to find all words that can be reduced in this way, and then find the longest one. This exercise is a little more challenging than most, so here are some suggestions: 1. You might want to write a function that takes a word and computes a list of all the words that can be formed by removing one letter. These are the “children” of the word. 2. Recursively, a word is reducible if any of its children are reducible. As a base case, you can consider the empty string reducible. 3. The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to add “I”, “a”, and the empty string. 4. To improve the performance of your program, you might want to memoize the words that are known to be reducible. You can see my solution at thinkpython.com/code/reducible.py. 126 Chapter 12. Tuples Chapter 13 Case study: data structure selection 13.1 Word frequency analysis As usual, you should at least attempt the following exercises before you read my solutions. Exercise 13.1 Write a program that reads a file, breaks each line into words, strips whitespace and punctuation from the words, and converts them to lowercase. 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: >>> import string >>> print string.punctuation !"#$%&'()*+,-./:;<=>?@[\]ˆ_`{|}˜ Also, you might consider using the string methods strip, replace and translate. Exercise 13.2 Go to Project Gutenberg (gutenberg.net) and download your favorite out-of- copyright book in plain text format. 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. 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? Download 1.04 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling