|
1 | 1 | """This module contains a code example related to
|
2 |
| -
|
3 | 2 | Think Python, 2nd Edition
|
4 | 3 | by Allen Downey
|
5 | 4 | http://thinkpython2.com
|
6 |
| -
|
7 | 5 | Copyright 2015 Allen Downey
|
8 |
| -
|
9 | 6 | License: http://creativecommons.org/licenses/by/4.0/
|
10 | 7 | """
|
11 | 8 |
|
|
14 | 11 | from rotate import rotate_word
|
15 | 12 |
|
16 | 13 |
|
17 |
| -def make_word_dict(): |
18 |
| - """Read the words in words.txt and return a dictionary |
19 |
| - that contains the words as keys""" |
20 |
| - d = dict() |
21 |
| - fin = open('words.txt') |
22 |
| - for line in fin: |
23 |
| - word = line.strip().lower() |
24 |
| - d[word] = None |
| 14 | +def make_word_list(): |
| 15 | + """Read the words in words.txt and return a list |
| 16 | + that contains the words.""" |
| 17 | + with open('words.txt') as fin: |
| 18 | + word_list = [] |
| 19 | + for line in fin: |
| 20 | + word = line.strip().lower() |
| 21 | + word_list.append(word) |
| 22 | + |
| 23 | + return word_list |
25 | 24 |
|
26 |
| - return d |
27 | 25 |
|
28 |
| - |
29 |
| -def rotate_pairs(word, word_dict): |
30 |
| - """Prints all words that can be generated by rotating word. |
31 |
| -
|
32 |
| - word: string |
33 |
| - word_dict: dictionary with words as keys |
| 26 | +def rotate_pairs(word_list): |
| 27 | + """Return list of all rotate pairs found in word_list. |
| 28 | + word_list: list of words |
34 | 29 | """
|
35 |
| - for i in range(1, 14): |
36 |
| - rotated = rotate_word(word, i) |
37 |
| - if rotated in word_dict: |
38 |
| - print(word, i, rotated) |
| 30 | + rotate_pairs = {} |
| 31 | + |
| 32 | + for word in word_list: |
| 33 | + first_letter = word[0] |
| 34 | + if first_letter.isupper(): |
| 35 | + ref_letter = ord('A') |
| 36 | + elif first_letter.islower(): |
| 37 | + ref_letter = ord('a') |
| 38 | + |
| 39 | + # Create a rotated word which always starts with "A" or "a" |
| 40 | + # and use it as a key to store the word in the rotate_pairs dict. |
| 41 | + rotated_word = rotate_word(word, ref_letter - ord(first_letter)) |
| 42 | + rotate_pairs.setdefault(rotated_word, []).append(word) |
| 43 | + |
| 44 | + # Rotate pairs are contained in the lists that have more than one word. |
| 45 | + rotate_pairs = [item for item in rotate_pairs.values() if len(item) > 1] |
| 46 | + return rotate_pairs |
39 | 47 |
|
40 | 48 |
|
41 | 49 | if __name__ == '__main__':
|
42 |
| - word_dict = make_word_dict() |
43 |
| - |
44 |
| - for word in word_dict: |
45 |
| - rotate_pairs(word, word_dict) |
| 50 | + word_list = make_word_list() |
| 51 | + all_rotate_pairs = rotate_pairs(word_list) |
0 commit comments