Skip to main content
 首页 » 编程设计

python之使用 lambda 编写一个 mutate 函数

2025年05月04日13三少

我需要编写一个名为“mutate to”的函数来计算由给定单词的单个突变生成的所有单词。 突变被定义为在字符串中插入一个字符、删除一个字符、替换一个字符或交换 2 个连续的字符。为简单起见,只考虑从 a 到 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] 

如何在一行中删除一个字符,然后交换字符串中的 2 个连续字符?

请您参考如下方法:

这算作 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 定义为这些情况生成的所有可能单词的集合。