我想在排列中删除字符串中的字符....
让我们说我有一个功能
def (string,char):
# remove char from string
假设我将aAabbAA
作为字符串,A作为字符,然后我希望字符串[aabb,aAabb,aabbA,aabbA, aabbAA,aAabbA ,aAabbA ]
作为输出A被删除3次,2次,1次。
我能做到这一点的最佳方式是什么?
非常感谢....
答案 0 :(得分:3)
这是一个使用递归的疯狂想法:
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'])
编辑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
答案 1 :(得分:1)
这是一个可行的解决方案。基本上我使用目标字符和空字符串的所有可能组合的产品。
from itertools import product
def deperm(st, c):
rsts = []
indexes = [i for i, s in enumerate(st) if s == c]
for i in product([c, ''], repeat=len(indexes)):
newst = ''
for j, ch in enumerate(st):
if j in indexes:
newst += i[indexes.index(j)]
else:
newst += ch
rsts.append(newst)
return rsts
for i in deperm('aAabbAA', 'A'):
print i
输出:
aAabbAA
aAabbA
aAabbA
aAabb
aabbAA
aabbA
aabbA
aabb
答案 2 :(得分:0)
像这样的递归算法可能对你有所帮助。对不起,我不是蟒蛇冠军,所以你可能需要自己调整语法。 Psuedo代码:
// returns a set of strings (permutations)
def permutation(string, char)
if len(string) == 0
return [] // return empty set
// get the set of permutations of suffix string recursively
set_of_perm_suffix = permutation(string[1:], char)
// prepend char to every string in set_of_perm
appended_set = prepend_char(set_of_perm_suffix , string[0])
// if the first char matches the one we should remove, we could either
// remove it or keep it.
if (string[0] == char)
return union_of_sets(set_of_perm_suffix , appended_set)
else
// the first char doesn't match the one we should remove,
// we need to keep it in every string of the set
return appended_set