不幸的是,我现在对递归函数无能为力,但考虑到如果在创建过程中不过滤,更多的字母/字符很容易爆炸成数十亿个潜在组合,我有一个通过迭代已知单词的古怪替代方案。无论如何,这些都必须在内存中。
[编辑] 删除了排序,因为它并没有真正提供任何好处,修复了我在迭代时错误地设置为 true 的问题
# Some letters, separated by space
letters = 'c a t b'
# letters = 't t a c b'
# # Assuming a word per line, this is the code to read it
# with open("words_on_file.txt", "r") as words:
# words_to_look_for = [x.strip() for x in words]
# print(words_to_look_for)
# Alternative for quick test
known_words = [
'cat',
'bat',
'a',
'cab',
'superman',
'ac',
'act',
'grumpycat',
'zoo',
'tab'
]
# Create a list of chars by splitting
list_letters = letters.split(" ")
for word in known_words:
# Create a list of chars
list_word = list(word)
if len(list_word) > len(list_letters):
# We cannot have longer words than we have count of letters
# print(word, "too long, skipping")
continue
# Now iterate over the chars in the word and see if we have
# enough chars/letters
temp_letters = list_letters[:]
# This was originally False as default, but if we iterate over each
# letter of the word and succeed we have a match
found = True
for char in list_word:
# print(char)
if char in temp_letters:
# Remove char so it cannot match again
# list.remove() takes only the first found
temp_letters.remove(char)
else:
# print(char, "not available")
found = False
break
if found is True:
print(word)
您可以从 itertools documentation 复制和粘贴产品功能并使用 ExtinctSpecie 提供的代码,它没有进一步的依赖关系,但是我发现不调整它会返回所有潜在选项,包括我没有立即理解的字符重复。
def product(*args, repeat=1):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)