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
// 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
这里有一个可行的解决方案。基本上,我使用目标字符和空字符串的所有可能组合的乘积。在
该输出:
^{pr2}$这里有一个使用递归的疯狂想法:
编辑:使用
^{pr2}$set
:编辑2:使用三元运算符:
^{3}$编辑3:
timeit
:像这样的递归算法可能会对您有所帮助。抱歉,我不是python的拥护者,所以您可能需要自己调整语法。Psuedo代码:
相关问题 更多 >
编程相关推荐