Skip to content

Commit f04a095

Browse files
Merge pull request #1 from DavidVFitzGerald/rotate_pairs
Update rotate_pairs.py
2 parents ce29336 + a88192a commit f04a095

File tree

1 file changed

+32
-26
lines changed

1 file changed

+32
-26
lines changed

code/rotate_pairs.py

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
"""This module contains a code example related to
2-
32
Think Python, 2nd Edition
43
by Allen Downey
54
http://thinkpython2.com
6-
75
Copyright 2015 Allen Downey
8-
96
License: http://creativecommons.org/licenses/by/4.0/
107
"""
118

@@ -14,32 +11,41 @@
1411
from rotate import rotate_word
1512

1613

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
2524

26-
return d
2725

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
3429
"""
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
3947

4048

4149
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

Comments
 (0)