获取置换中移除字符的字符串列表

2024-04-26 09:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从一个字符串中删除一个字符。。。。在

假设我有一个函数

def (string,char):
    # remove char from string

假设我有aAabbAA作为字符串和一个as char,那么我希望字符串{}作为输出,即A被删除3次,2次,1次。在

我最好的办法是什么??在

非常感谢。。。。在


Tags: 函数字符串fromstringdefas字符remove
3条回答

这里有一个可行的解决方案。基本上,我使用目标字符和空字符串的所有可能组合的乘积。在

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

该输出:

^{pr2}$

这里有一个使用递归的疯狂想法:

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

^{pr2}$

编辑2:使用三元运算符:

^{3}$

编辑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

像这样的递归算法可能会对您有所帮助。抱歉,我不是python的拥护者,所以您可能需要自己调整语法。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

相关问题 更多 >