【问题标题】:Iterative algorithm to generate all combinations with any number of lists生成具有任意数量列表的所有组合的迭代算法
【发布时间】:2021-04-06 02:17:22
【问题描述】:

我有一个问题,我试图自己解决,但我不确定是否有更好的算法来解决这个问题。 假设我有一个包含整个字母表的字典。 我可以调用传递字符串的函数,该字符串指示与要用于生成输出的列表相关的键。我可以多次添加相同的密钥。 我想生成它们之间所有可能的组合并在没有递归的情况下解决它。

我尝试使用下面的蛮力方法自己解决问题,但我想知道是否有更好的方法。

我的尝试如下:

words_dict = {
    2: ['a', 'b', 'c'],
    3: ['d', 'e', 'f'],
    4: ['g', 'h', 'i'],
    5: ['j', 'k', 'l'],
    6: ['m', 'n', 'o'],
    7: ['p', 'q', 'r'],
    8: ['t', 'u', 'v', 'w'],
    9: ['x', 'y', 'z'],
}


def generate_combinations(numbers):
    words_to_expand = words_dict[int(numbers[0])]
    for i in range(1, len(numbers)):
        letters_list = words_dict[int(numbers[i])]
        aux_words_expanded = []
        for incomplete_word in words_to_expand:
            for letter_to_combine in letters_list:
                expanded_word = incomplete_word + letter_to_combine
                aux_words_expanded.append(expanded_word)
            words_to_expand = aux_words_expanded

    print(words_to_expand)
    return words_to_expand
    pass


generate_combinations('234')

【问题讨论】:

    标签: python algorithm combinations


    【解决方案1】:

    @MmBaguette 的回答为您指明了正确的方向。 建议使用itertools

    完整的功能应该是这样的:

    def generate_combinations(numbers):
        words = []
        indexes = (int(val) for val in numbers)
        letter_groups = [words_dict[idx] for idx in indexes]
        for entry in itertools.product(*letter_groups):
            words.append("".join(entry))
        print(words)
        print(len(words))
    

    甚至更短:

    def generate_combinations(numbers):
        indexes = (int(val) for val in numbers)
        letter_groups = [words_dict[idx] for idx in indexes]
        words = list("".join(entry)
            for entry in itertools.product(*letter_groups))
        print(words)
        print(len(words))
    
    

    【讨论】:

      【解决方案2】:

      这是一种更 Pythonic 的方法

      import itertools
      my_list = ["a", "b", "c", "d"]
      itertools.combinations(my_list) #returns generator of combinations
      itertools.permutations(my_list, 3) #same but with length of results specified
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-18
        • 2023-03-18
        • 2020-07-11
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 2014-04-12
        • 2015-10-13
        相关资源
        最近更新 更多