![](/img/trans.png)
[英]Given a number, generate a list of all possible combination of X and O with length n
[英]Generate all possible combination with “N” length from given words list (Looking for no repeat)
我想生成給定長度的單詞句子。 在這里,我想得到 output 沒有任何重復的字符或單詞。
使用當前代碼,我正在接收輸出
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
但我想收到帶有隨機單詞的 output,因為句子中沒有重復的單詞
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)
作為對您的評論的回應,要在單詞之間添加空格,您可以修改您的包裝器 function 如下:
def printAllKLength(set, k):
set = {word + " " for word in set}
n = len(set)
printAllKLengthRec(set, "", n, k)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.