📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division121314def signature(s):15"""Returns the signature of this string.1617Signature is a string that contains all of the letters in order.1819s: string20"""21# TODO: rewrite using sorted()22t = list(s)23t.sort()24t = ''.join(t)25return t262728def all_anagrams(filename):29"""Finds all anagrams in a list of words.3031filename: string filename of the word list3233Returns: a map from each word to a list of its anagrams.34"""35d = {}36for line in open(filename):37word = line.strip().lower()38t = signature(word)3940# TODO: rewrite using defaultdict41if t not in d:42d[t] = [word]43else:44d[t].append(word)45return d464748def print_anagram_sets(d):49"""Prints the anagram sets in d.5051d: map from words to list of their anagrams52"""53for v in d.values():54if len(v) > 1:55print(len(v), v)565758def print_anagram_sets_in_order(d):59"""Prints the anagram sets in d in decreasing order of size.6061d: map from words to list of their anagrams62"""63# make a list of (length, word pairs)64t = []65for v in d.values():66if len(v) > 1:67t.append((len(v), v))6869# sort in ascending order of length70t.sort()7172# print the sorted list73for x in t:74print(x)757677def filter_length(d, n):78"""Select only the words in d that have n letters.7980d: map from word to list of anagrams81n: integer number of letters8283returns: new map from word to list of anagrams84"""85res = {}86for word, anagrams in d.items():87if len(word) == n:88res[word] = anagrams89return res909192if __name__ == '__main__':93anagram_map = all_anagrams('words.txt')94print_anagram_sets_in_order(anagram_map)9596eight_letters = filter_length(anagram_map, 8)97print_anagram_sets_in_order(eight_letters)9899100101