algorithm - 给定一个字符串列表,打印所有字符串组合,从每个字符串中选择一个字符

标签 algorithm combinations computer-science

我正在尝试找到解决此问题的最有效方法。目前,我有一个解决方案,我在其中创建字符串到它们的字符串长度的映射,然后使用辅助函数将字符拼接在一起并在我进行时递减映射列表。当前值递减为 0 时,其左侧的数字递减 1,然后该数字 + 其右侧的数字重置为其长度 1。其实现如下所示:

def printCombinations(s):
    data_lens = []
    s = [x for x in s if x]
    for idx,val in enumerate(s): #create string length mapping list
        if len(val) == 0:
            s = s[0:idx]+s[idx+1:] #remove empty strings
            idx = idx -1
        else:
            data_lens.append(len(s[idx])-1)
    total_combos = 1
    for i in data_lens:
        total_combos = total_combos * (i+1) #total combos = lengths of the strings multiplied by each other
    current_index = len(s)-1

    while total_combos > 0:
        data_lens_copy = data_lens[:]
        if data_lens[current_index] >= 0: #if current number >= 0
            print(generateString(data_lens_copy, s))
            data_lens[current_index] -= 1
            total_combos -=1
        else:
            if current_index > 0:
                while data_lens[current_index] <= 0: #shift left while <= 0
                    current_index -= 1

                if data_lens[current_index] >= 0:
                    data_lens[current_index] -= 1
                    for i in range(current_index+1,len(s)):
                        data_lens[i] = len(s[i])-1
                    current_index = len(s)-1

def generateString(indices, strings):
    resultStr = ""
    for i in range(len(indices)-1,-1,-1):
        current_str = strings[i]
        current_index = indices[i]
        if current_str != "":
            resultStr = current_str[current_index] + resultStr
        indices[i] -= 1
    return resultStr

虽然这个解决方案完成了工作,但它创建了一个大小相等的映射列表,并在数字达到 0 时迭代地将映射值重置为右侧。打印出包含 1 个字符的所有字符串组合的更有效方法是什么来自每个字符串元素?

ex: ["dog","cat"] -> dc,da,dt,oc,oa,ot,gc,ga,gt

最佳答案

如果您不想使用 itertools.product 并且希望了解算法,一种方法是定义递归算法。它比原始代码快(大约 16 倍),但与涉及的 print 的比较是不确定的。

def product(item,*args):
    # termination condition: if only one string, yield the characters.
    if not args:
        yield from item
    else:
        # Recursion, yield the character for each item,
        # combined with the results of the remaining strings
        for c in item:
            for d in product(*args):
                yield c + d

print(list(product('dog','cat')))
print(list(product('ab','cd','def')))

输出:

['dc', 'da', 'dt', 'oc', 'oa', 'ot', 'gc', 'ga', 'gt']
['acd', 'ace', 'acf', 'add', 'ade', 'adf', 'bcd', 'bce', 'bcf', 'bdd', 'bde', 'bdf']

关于algorithm - 给定一个字符串列表,打印所有字符串组合,从每个字符串中选择一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54285956/

相关文章:

java - 枚举子集的空间复杂度是多少?

javascript - 多重约束复杂数据的最佳组合算法

algorithm - 两个线性嵌套循环的 Big-theta 运行时间,对于外部的每次迭代,内部运行的次数是外部的一半。

sockets - 当两台计算机通过网络连接进行交互时,它们首先必须建立套接字连接吗?

algorithm - Viola-Jones 的人脸检测声称拥有 18 万个特征

python - 什么会更好地实现锯齿列表的字典顺序的所有组合?

algorithm - 双动窗算法

java - 递归添加子集

javascript - 随机选择组合,以便每个元素精确地代表两次

arrays - 数组和散列映射在访问时如何保持恒定时间?