【问题标题】:Given a list of strings, print all combinations of strings choosing 1 character from each给定一个字符串列表,打印字符串的所有组合,从每个组合中选择 1 个字符
【发布时间】:2019-01-21 08:31:55
【问题描述】:

我正在尝试找到解决此问题的最有效方法。目前,我有一个解决方案,在该解决方案中,我创建了字符串与其字符串长度的映射,然后使用辅助函数将字符拼接在一起,并在执行过程中递减映射列表。当当前值减为 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"] -&gt; dc,da,dt,oc,oa,ot,gc,ga,gt

【问题讨论】:

  • itertools.product
  • 澄清:我不是在寻找一个图书馆来完成这个。相反,我试图了解如何自己实现这种算法。这里的目标是了解此类问题背后的算法技术。也许删除python标签?以为我会在那里添加它,因为我的实现是在 Python 中
  • 您已经在混合基数系统中实现了从最大值total_combos 到零的计数(其中第 k 个数字的基数是第 k 个字符串的长度)。这是相当有效的方法。也确实存在简单的递归方式(适用于不是很长的项目)。恕我直言,最好删除 Python 标记

标签: algorithm combinations computer-science


【解决方案1】:

如果您不想使用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']

【讨论】:

  • 很好的解决方案,但我想知道您是否可以提供一个替代解决方案,它在执行时打印结果,而不是在处理完所有结果并且传递的参数是数组而不是动态数字论据。
  • @btrballin 代替*args 使用args,并在递归调用中传递args[0],args[1:]for item in product('dog','cat'): print(item) 会按原样打印。由于递归,您无法真正打印函数本身……它会打印中间结果。
猜你喜欢
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 2021-05-27
  • 1970-01-01
  • 2012-01-22
  • 2017-11-23
  • 2022-12-20
相关资源
最近更新 更多