【发布时间】: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