Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96169
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
import anagram_sets
15
16
17
def metathesis_pairs(d):
18
"""Print all pairs of words that differ by swapping two letters.
19
20
d: map from word to list of anagrams
21
"""
22
for anagrams in d.values():
23
for word1 in anagrams:
24
for word2 in anagrams:
25
if word1 < word2 and word_distance(word1, word2) == 2:
26
print(word1, word2)
27
28
29
def word_distance(word1, word2):
30
"""Computes the number of differences between two words.
31
32
word1, word2: strings
33
34
Returns: integer
35
"""
36
assert len(word1) == len(word2)
37
38
count = 0
39
for c1, c2 in zip(word1, word2):
40
if c1 != c2:
41
count += 1
42
43
return count
44
45
46
if __name__ == '__main__':
47
sets = anagram_sets.all_anagrams('words.txt')
48
metathesis_pairs(sets)
49
50