gpt4 book ai didi

python - 生成列表中每个单词的所有组合和排列

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:10 24 4
gpt4 key购买 nike

给定一个输入词列表,写一个程序可以生成所有单词,这些单词可以使用每个输入单词的字符子集组成。

例如,如果输入单词列表是:猫垫子

输出文件如下所示:AC吨在塔行为猫

我是 pythonic 代码的新手。我有已经在运行的代码,但它不适用于像“光合作用”这样的很长的词。我可能缺少什么?

from itertools import permutations
def x():
y = ["cat", "mat"]
for i in y:
z = [perm for length in range(1, len(i) + 1) for perm in permutations(i, length)]
for i in z:
a = ''.join(i)
print(a)
x()

最佳答案

计算“光合作用”所有排列的结果需要花费大量时间。使用基于生成器的方法,如下所示。

from itertools import permutations

def get_perms(value, length):
for l in range(length):
for perm in permutations(value, l):
yield ''.join(perm)
else:
return []

def x():
y = ["photosynthesis"]
for i in y:
perms = get_perms(i, len(i))
for item in perms:
print(item)

x()

关于python - 生成列表中每个单词的所有组合和排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com