Python 具有若干静态元素的快速置换

Python 具有若干静态元素的快速置换,python,algorithm,permutation,Python,Algorithm,Permutation,我有一个函数,它得到一个字符串,比如ABA?问号是一个通配符,可以是a或B。传递的字符串可以有多个通配符。它应该将多个字符串作为一个数组返回,并包含所有可能的解决方案。我的代码太慢了。我是python新手,所以要找到一个好的解决方案有点困难 ABA什么时候?如果通过,它应该返回['ABAA','ABAB'] from itertools import product def possibilities(param): result = [] for i in product([

我有一个函数,它得到一个字符串,比如ABA?问号是一个通配符,可以是a或B。传递的字符串可以有多个通配符。它应该将多个字符串作为一个数组返回,并包含所有可能的解决方案。我的代码太慢了。我是python新手,所以要找到一个好的解决方案有点困难

ABA什么时候?如果通过,它应该返回['ABAA','ABAB']

from itertools import product

def possibilities(param):
    result = []
    for i in product([A,B], repeat=param.count('?')):
        string = param
        for p in [i]:
            for val in p:
                string = string.replace('?', str(val), 1)
            result.append(string)
    return result
您应该使用一个循环,以便可以循环输出。如果您有很多通配符,那么完整的列表将需要大量内存才能完全存储,因为它会以指数级增长

import itertools

def possibilties(s):
    n_wildcard = s.count('?')

    for subs in itertools.product(['A','B'], repeat=n_wildcard):
        subs = iter(subs)
        yield ''.join([x if x != '?' else subs.next() for x in s])

for p in possibilties('A?BA?'):
    print p
这使得:

AABAA
AABAB
ABBAA
ABBAB

我不明白你的问题,你想在每个字母后面加上一个字母而不重复吗?因此,如果ABC输出:ABCA ABCB ABCC???无论如何,在这里你可以找到你想要的:没有C,唯一的字母是AB和通配符,它可以是a或比特,肯定是一个更好的解决方案,但需要很长时间才能完成,它应该要快10%,但我真的不知道这是如何实现的。