从给定的单词列表中生成具有“N”长度的所有可能组合(寻找不重复)
Posted
技术标签:
【中文标题】从给定的单词列表中生成具有“N”长度的所有可能组合(寻找不重复)【英文标题】:Generate all possible combination with "N" length from given words list (Looking for no repeat) 【发布时间】:2021-01-21 14:51:55 【问题描述】:我想生成给定长度的单词句子。在这里,我想获得没有任何重复字符或单词的输出。
使用当前代码,我正在接收输出
example example example example example
example example example example example2
example example example example example3
example example example example example4
example example example example example5
example example example example example6
example example example example example7
example example example example example8
example example example example example9
example example example example2 example
example example example example2 example2
但我想接收带有随机单词的输出,因为句子中没有任何重复的单词
example example1 example2 example3 example4
example1 example2 example3 example4 example5
example5 example1 example2 example3 example4
example6 example4 example2 example5 example1
这里是代码
import numpy as np
# Python 3 program to print all
# possible strings of length k
# The method that prints all
# possible strings of length k.
# It is mainly a wrapper over
# recursive function printAllKLengthRec()
def printAllKLength(set, k):
n = len(set)
printAllKLengthRec(set, "", n, k)
# The main recursive method
# to print all possible
# strings of length k
def printAllKLengthRec(set, prefix, n, k):
# Base case: k is 0,
# print prefix
if (k == 0) :
print(prefix)
return
# One by one add all characters
# from set and recursively
# call for k equals to k-1
for i in range(n):
# Next character of input added
newPrefix = prefix + set[i]
# k is decreased, because
# we have added a new character
printAllKLengthRec(set, newPrefix, n, k - 1)
# Driver Code
if __name__ == "__main__":
print("\nSecond Test")
set2 = ['example ', 'example2 ', 'example3 ', 'example4 ', 'example5 ', 'example6 ', 'example7 ', 'example8 ', 'example9 ']
k = 5
printAllKLength(set2, k)
# This code is contributed
# by ChitraNayal
【问题讨论】:
我们不会为你做作业@Kranthi :D,但考虑排序和回溯!先写在纸上,再写代码! 试试itertools.permutations
。 docs.python.org/3/library/itertools.html#itertools.permutations
你能更好地解释一下你想在你的输出中得到什么
@RohitashwaNigam 当然,伙计。
@codebyAbhishekBharti 我想生成 N 长度的单词,句子中没有重复单词
【参考方案1】:
你只需要记录你在你的系列中没有使用过的角色,所以你不要重复它们。在这里,我有一个名为 remaining_char 的列表理解:
def printAllKLength(set, k):
n = len(set)
printAllKLengthRec(set, "", n, k)
def printAllKLengthRec(set, prefix, n, k):
if (k == 0):
print(prefix)
return
remaining_char = [char for char in set if char not in prefix]
for i in range(len(remaining_char)):
newPrefix = prefix + remaining_char[i]
printAllKLengthRec(set, newPrefix, n, k - 1)
【讨论】:
我正在尝试在单词之间添加空格,我尝试了很多方法,但都失败了,您能帮帮我吗? @Kranthi 查看我的第二个答案,如果它适合您,请点赞。干杯。【参考方案2】:响应您的评论,要在单词之间添加空格,您可以修改您的包装函数,如下所示:
def printAllKLength(set, k):
set = word + " " for word in set
n = len(set)
printAllKLengthRec(set, "", n, k)
【讨论】:
以上是关于从给定的单词列表中生成具有“N”长度的所有可能组合(寻找不重复)的主要内容,如果未能解决你的问题,请参考以下文章