-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path52.py
More file actions
49 lines (31 loc) · 1.7 KB
/
52.py
File metadata and controls
49 lines (31 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""Problem 52: Write a function nearly_equal to test whether two strings are nearly equal. Two strings a and
b are nearly equal when a can be generated by a single mutation on b."""
import string
def insert_char(input_string, character, pos):
return input_string[:pos] + character + input_string[pos:]
def replace_char(input_string, character, pos):
return input_string[:pos] + character + input_string[pos + 1:]
def swap_chars(input_string, pos1, pos2):
return replace_char(replace_char(input_string, input_string[pos1], pos2), input_string[pos2], pos1)
def mutate(input_string):
result = {} # define the result as a set: unordered collection of unique values
alphabet = string.ascii_lowercase # all lowercase letters of the alphabet
result = {
replace_char(input_string, '', s[0]) for s in enumerate(input_string)
} # all mutations of input_string with 1 char removed
result = result.union(
{insert_char(input_string, letter, i) for i in range(len(input_string) + 1) for letter in alphabet}
) # all mutations of input string with 1 char inserted
result = result.union(
{replace_char(input_string, letter, s[0]) for s in enumerate(input_string) for letter in alphabet}
) # all mutations of input string with 1 char replaced
result = result.union(
{swap_chars(input_string, i, i + 1) for i in range(len(input_string) - 1)}
) # all mutations of input string with consecutive chars swapped
return result
def nearly_equal(string1, string2):
return string1 in mutate(string2)
print(nearly_equal('python', 'perl'))
print(nearly_equal('perl', 'pearl'))
print(nearly_equal('python', 'jython'))
print(nearly_equal('man', 'woman'))