从给定的单词列表中生成长度为 "N" 的所有可能组合(寻找无重复)

Generate all possible combination with "N" length from given words list (Looking for no repeat)

我想生成给定长度的单词句子。在这里我想得到没有任何字符或单词重复的输出。

使用当前代码,我正在接收输出

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 

您只需要记录您的集中没有使用过的字符,这样您就不会重复它们。这里我有一个名为 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)

针对您的评论,要在单词之间添加 space,您可以按如下方式修改包装函数:

def printAllKLength(set, k):
    set = {word + "   " for word in set}
    n = len(set)
    printAllKLengthRec(set, "", n, k)