我需要编写一个名为" mutate to"的函数。计算给定单词上单个变异生成的所有单词。 突变定义为插入字符,删除字符,替换字符或交换字符串中的2个连续字符。为简单起见,只考虑字母froma到z
例如:
words = mutate("hello")
'helo' in words
True
'cello' in words
True
'helol' in words
True
这是我到目前为止设法完成的代码:
letters = ['a','b','c','d','e','f','g','h','i','j','k','m','l','n','o','p','q','r','s','t' ,'u','v','w','x','y','z']
mutate = lambda x: [''.join([x[:i], l, x[i+1:len(x)]])
for i in range(len(x))
for l in letters]
我怎样才能在一行中删除一个字符,并在一个字符串中交换两个连续的字符?
答案 0 :(得分:1)
这是否算作lambda
使用?
import string
def f1(word):
return set(word[:i] + c + word[i:] for i in range(len(word) + 1) for c in string.ascii_lowercase)
def f2(word):
return set((word[:i] + word[i + 1:]) for i in range(len(word)))
def f3(word):
return set((word[:i] + c + word[i + 1:] for i in range(len(word)) for c in string.ascii_lowercase))
def f4(word):
return set((word[:i] + word[i + 1] + word[i] + word[i + 2:]) for i in range(len(word) - 1))
mutate = lambda word: set(f1(word) | f2(word) | f3(word) | f4(word))
这为四种情况中的每一种定义了一个函数,然后将mutate
定义为由这些情况生成的所有可能单词的集合。