获取字符串列表,其中字符已在排列中删除 [英] Getting a list of strings with character removed in permutation
本文介绍了获取字符串列表,其中字符已在排列中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从排列中的字符串中删除一个字符....
I want to remove a character from a string in permutation....
让我们说我有一个功能
def (string,char):
# remove char from string
假设我将aAabbAA
作为字符串,将A作为char,然后我希望将作为输出的字符串[aabb,aAabb,aabbA,aabbA, aabbAA,aAabbA ,aAabbA ]
删除3次,2次,1次.
Say I have aAabbAA
as string and A as char then I want the strings [aabb,aAabb,aabbA,aabbA, aabbAA,aAabbA ,aAabbA ]
as output that is A gets removed 3 times , 2 times , 1 times.
我能做到的最好方法是什么?
What is the best way in which I can do that ??
非常感谢....
推荐答案
这是使用递归的一个疯狂主意:
Here is one crazy idea using recursion:
def f(s, c, start):
i = s.find(c, start)
if i < 0:
return [s]
else:
return f(s, c, i+1) + f(s[:i]+s[i+1:], c, i)
s = 'aAabbAA'
print f(s, 'A', 0)
# ['aAabbAA', 'aAabbA', 'aAabbA', 'aAabb', 'aabbAA', 'aabbA', 'aabbA', 'aabb']
使用set
:
def f(s, c, start):
i = s.find(c, start)
if i < 0:
return set([s])
else:
return set.union(f(s, c, i+1), f(s[:i]+s[i+1:], c, i))
s = 'aAabbAA'
print f(s, 'A', 0)
# set(['aAabbA', 'aabbAA', 'aAabbAA', 'aabb', 'aAabb', 'aabbA'])
使用三元运算符:
def f(s, c, start):
i = s.find(c, start)
return [s] if i < 0 else f(s, c, i+1) + f(s[:i]+s[i+1:], c, i)
s = 'aAabbAA'
print f(s, 'A', 0)
# ['aAabbAA', 'aAabbA', 'aAabbA', 'aAabb', 'aabbAA', 'aabbA', 'aabbA', 'aabb']
timeit
:
In [32]: timeit.timeit('x = f("aAabbAA", "A", 0)',
'from test3 import f', number=10000)
Out[32]: 0.11674594879150391
In [33]: timeit.timeit('x = deperm("aAabbAA", "A")',
'from test4 import deperm', number=10000)
Out[33]: 0.35839986801147461
In [34]: timeit.timeit('x = f("aAabbAA"*6, "A", 0)',
'from test3 import f', number=1)
Out[34]: 0.45998811721801758
In [35]: timeit.timeit('x = deperm("aAabbAA"*6, "A")',
'from test4 import deperm', number=1)
Out[35]: 7.8437530994415283
这篇关于获取字符串列表,其中字符已在排列中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文