我想从排列中的字符串中删除字符.
让我们说我有一个功能
def (string,char):
# remove char from string
假设我将aAabbAA作为字符串,将A作为char,然后我希望将字符串[aabb,aAabb,aabbA,aabbA,aabbAA,aAabbA,aAabbA]作为输出,将A删除3次,2次,1次.
我能做到的最好方法是什么?
非常感谢….
解决方法:
这是使用递归的一个疯狂想法:
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']
编辑:使用设置:
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'])
编辑2:使用三元运算符:
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']
编辑3: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