![](/img/trans.png)
[英]How to write most efficient algorithm to find all possible permutation in list of strings
[英]How to find all possible permutation of two strings within constant length
我想在恆定長度(5)
內找到兩個字符串列表的所有可能排列。 假設list_1 = ["A"]
和list_2 = ["BB"]
。
所有可能的組合是:
A A A A A
A A A BB
A A BB A
A BB A A
BB A A A
A BB BB
BB A BB
BB BB A
我試圖用下面的代碼來實現它,但我不確定如何為它定義長度 5。
import itertools
from itertools import permutations
list_1 = ["A"]
list_2 = ["BB"]
unique_combinations = []
permut = itertools.permutations(list_1, 5)
for comb in permut:
zipped = zip(comb, list_2)
unique_combinations.append(list(zipped))
print(unique_combinations)
您可以執行以下操作:
import itertools
unique_combinations = []
permut = itertools.product(["A","B"], repeat=5)
for comb in permut:
l = "".join(comb)
c_bb = l.count("BB")
c_a = l.count("A")
if 2*c_bb + c_a == 5:
unique_combinations.append(l)
print(unique_combinations)
這將給出:
['AAAAA', 'AAABB', 'AABBA', 'ABBAA', 'ABBBB', 'BBAAA', 'BBABB', 'BBBBA']
首先找到所有長度為 5 的字符串,由 5 個元素組成,要么是“A”,要么是“B”。 然后使用string.count
計算您感興趣的每個子字符串的出現次數,如果等於 5 則保存它。
您可以使用itertools.product
找到'A'
和'BB'
所有可能組合(從 3 到 5 repeat
,因為這些是可接受答案中的元素數),然后根據它們的總長度進行過濾是 5 個字符:
import itertools
all_options = []
for i in range(3,6):
all_options += list(itertools.product(['A', 'BB'], repeat=i))
all_options = [i for i in all_options if len(''.join(i)) == 5]
print(all_options)
輸出:
[('A', 'BB', 'BB'), ('BB', 'A', 'BB'), ('BB', 'BB', 'A'), ('A', 'A', 'A', 'BB'), ('A', 'A', 'BB', 'A'), ('A', 'BB', 'A', 'A'), ('BB', 'A', 'A', 'A'), ('A', 'A', 'A', 'A', 'A')]
使用遞歸:
list_1 = ["A"]
list_2 = ["BB"]
size = 5
strs = list_1 + list_2
res = []
def helper(strs, size, cur, res):
if size == 0:
res.append(cur)
return
if size < 0:
return
for s in strs:
helper(strs, size-len(s), cur+[s], res)
helper(strs, size, [], res)
print(res)
無遞歸:
list_1 = ["A"]
list_2 = ["BB"]
size = 5
strs = list_1 + list_2
res = []
q = [[]]
while q:
t = q.pop()
for s in strs:
cur = t + [s]
cursize = len(''.join(cur))
if cursize == size:
res.append(cur)
elif cursize < size:
q.append(cur)
print(res)
你需要一個這樣的遞歸函數:
def f(words, N, current = ""):
if(len(current)<N):
for i in words:
f(words, N, current+i)
elif(len(current)==N):
print(current)
f(["A", "BB"], 5)
編輯:不幸的是,如果列表中的兩個或多個單詞共享相同的字母,則此函數返回重復項。 所以正確的方法應該是用所有返回填充一個列表,然后消除重復項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.