-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path51.py
More file actions
43 lines (28 loc) · 1.66 KB
/
51.py
File metadata and controls
43 lines (28 loc) · 1.66 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
"""Problem 51: Write a function mutate to compute all words generated by a single mutation on a given word. A
mutation is defined as inserting a character, deleting a character, replacing a character, or swapping 2 consecutive
characters in a string. For simplicity consider only letters from a to z."""
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
mutations = mutate("Bee Movie")
print("Bee Movi" in mutations)