字符串为'january',
如何生成以下案例:
case1(替换1个字符)=>;取j并将其替换为所有ASCII字母(a-z)。然后对a,n,u,a,r,y做同样的处理
基本上我们会
(一年,一年,。。。。。,Zanuary)+(一月,jBanuary…..jZanuary)+…+(januarA,januarB,…,januarZ)
我已经用下面的代码完成了这一部分,但是,由于有很多排列,我不知道如何对多个字母执行此操作。在
monthName= 'january'
asci_letters = ['a' , 'b' , .... , 'z']
lst = list(monthName)
indxs = [i for i , _ in enumerate(monthName)]
oneLetter=[]
for i in indxs:
word = monthName
pos = list(word)
for j in asci_letters:
pos[i] = j
changed = ("".join(pos))
oneLetter.append(changed)
案例2:取2个字符并替换它们: (AAnuary,ABnuary,…,AZanuary)+(BAnuary,BBanuary。。。。,BZanuary)+(AaAuary,AaBuary,…,AaZuary)+。。。。。。+(januaAB。。。。,雅努阿兹)
案例3:对3个字符执行相同的操作
案例7:对7个字符(字符串长度)执行相同操作
总而言之,我想创建所有可能的替换情况,1个字母,2个字母,3个字母,直到字符串中的所有字母。在
很可能你不能把所有这些排列都记在记忆里,因为它很快就会变得非常拥挤。在
但是要获得案例的所有索引,可以使用
itertools.combinations
。对于1,它将给出单个指数:同样,您可以得到案例2-7的索引:
^{pr2}$那么只需在给定的索引处插入
itertools.product
的itertools.product
:同样地,对于不同的重复,给出了“案例”。在
把这些放在一起:
然后,您可以通过以下方法获得每种情况下所需的所有排列:
或者如果你需要所有这些:
但这需要大量的内存。在
您可以为此使用
itertools.combinations_with_replacement
,这将给您一个包含所有置换的iterator
:不要试图将这个
iterator
转换为一个包含所有值的列表,因为您可能会得到一个MemoryException
。在对于您的距离,您可能需要使用python
distance
包。(您需要先通过pip安装它)。在对于您的情况,您希望获得长度为7的字符a-z的所有组合(由于一月):
^{pr2}$这将在
product
和permutations
的帮助下完成您想要的一切:相关问题 更多 >
编程相关推荐