Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96165
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
15
def signature(s):
16
"""Returns the signature of this string.
17
18
Signature is a string that contains all of the letters in order.
19
20
s: string
21
"""
22
# TODO: rewrite using sorted()
23
t = list(s)
24
t.sort()
25
t = ''.join(t)
26
return t
27
28
29
def all_anagrams(filename):
30
"""Finds all anagrams in a list of words.
31
32
filename: string filename of the word list
33
34
Returns: a map from each word to a list of its anagrams.
35
"""
36
d = {}
37
for line in open(filename):
38
word = line.strip().lower()
39
t = signature(word)
40
41
# TODO: rewrite using defaultdict
42
if t not in d:
43
d[t] = [word]
44
else:
45
d[t].append(word)
46
return d
47
48
49
def print_anagram_sets(d):
50
"""Prints the anagram sets in d.
51
52
d: map from words to list of their anagrams
53
"""
54
for v in d.values():
55
if len(v) > 1:
56
print(len(v), v)
57
58
59
def print_anagram_sets_in_order(d):
60
"""Prints the anagram sets in d in decreasing order of size.
61
62
d: map from words to list of their anagrams
63
"""
64
# make a list of (length, word pairs)
65
t = []
66
for v in d.values():
67
if len(v) > 1:
68
t.append((len(v), v))
69
70
# sort in ascending order of length
71
t.sort()
72
73
# print the sorted list
74
for x in t:
75
print(x)
76
77
78
def filter_length(d, n):
79
"""Select only the words in d that have n letters.
80
81
d: map from word to list of anagrams
82
n: integer number of letters
83
84
returns: new map from word to list of anagrams
85
"""
86
res = {}
87
for word, anagrams in d.items():
88
if len(word) == n:
89
res[word] = anagrams
90
return res
91
92
93
if __name__ == '__main__':
94
anagram_map = all_anagrams('words.txt')
95
print_anagram_sets_in_order(anagram_map)
96
97
eight_letters = filter_length(anagram_map, 8)
98
print_anagram_sets_in_order(eight_letters)
99
100
101