Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update of rotate_pairs #70

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
58 changes: 32 additions & 26 deletions code/rotate_pairs.py
@@ -1,11 +1,8 @@
"""This module contains a code example related to

Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com

Copyright 2015 Allen Downey

License: http://creativecommons.org/licenses/by/4.0/
"""

Expand All @@ -14,32 +11,41 @@
from rotate import rotate_word


def make_word_dict():
"""Read the words in words.txt and return a dictionary
that contains the words as keys"""
d = dict()
fin = open('words.txt')
for line in fin:
word = line.strip().lower()
d[word] = None
def make_word_list():
"""Read the words in words.txt and return a list
that contains the words."""
with open('words.txt') as fin:
word_list = []
for line in fin:
word = line.strip().lower()
word_list.append(word)

return word_list

return d


def rotate_pairs(word, word_dict):
"""Prints all words that can be generated by rotating word.

word: string
word_dict: dictionary with words as keys
def rotate_pairs(word_list):
"""Return list of all rotate pairs found in word_list.
word_list: list of words
"""
for i in range(1, 14):
rotated = rotate_word(word, i)
if rotated in word_dict:
print(word, i, rotated)
rotate_pairs = {}

for word in word_list:
first_letter = word[0]
if first_letter.isupper():
ref_letter = ord('A')
elif first_letter.islower():
ref_letter = ord('a')

# Create a rotated word which always starts with "A" or "a"
# and use it as a key to store the word in the rotate_pairs dict.
rotated_word = rotate_word(word, ref_letter - ord(first_letter))
rotate_pairs.setdefault(rotated_word, []).append(word)

# Rotate pairs are contained in the lists that have more than one word.
rotate_pairs = [item for item in rotate_pairs.values() if len(item) > 1]
return rotate_pairs


if __name__ == '__main__':
word_dict = make_word_dict()

for word in word_dict:
rotate_pairs(word, word_dict)
word_list = make_word_list()
all_rotate_pairs = rotate_pairs(word_list)