[英]How to sequentially populate a list of given length from another list of elements and recursively find all possible combinations that satisfy?
我有一個 ['missing', 'missing', 'missing', 'missing', ' missing '] 形式的種子列表。 我想通過從['e1','e2']形式的另一個列表樣本中采樣來順序(或者)填充它。
實際上,我想按順序填充lst直到所有元素都填充有樣本(或者選擇 e1 和 e2,總是從 e1 開始)或滿足停止條件。 一組步驟將導致一個這樣的組合,我想遞歸地找到所有。
更具體地說,考慮以下示例。
組合例一:
0: ['missing', 'e1, 'missing', 'missing', 'missing']
1: ['missing', 'e1, 'e2', 'missing', 'missing']
2: ['missing', 'e1, 'e2', 'missing', 'e1']
3: ['missing', 'e1, 'e2', 'e2', 'e1']
4: ['e1', 'e1, 'e2', 'e2', 'e1']
如您所見,通過第 4 步填充了整個列表。 這是一種可能的組合,我想逐步生成所有可能的組合。
這是另一個插圖。 請注意,和以前一樣,“e1”和“e2”是交替選擇的,“e1”總是首先選擇。 組合示例2:
0: ['e1', 'missing, 'missing', 'missing', 'missing']
1: ['e1', 'e2, 'missing', 'missing', 'missing']
2: ['e1', 'e2, 'e1', 'missing', 'missing']
3: ['e1', 'e2, 'e2', 'e2', 'missing']
4: ['e1', 'e2, 'e1', 'e2', 'e1']
除了“整個列表已填滿”之外,我可能會在生成過程的每個步驟中進行任意終止檢查(對於我們正在嘗試的任何給定組合)。 例如,如果 check_termination(current_lst) 滿足任何一個組合中的給定步驟,那么我會中斷遞歸並繼續下一個組合。 什么是實現這一目標的有效的 Pythonic 方式?
好的,所以我構建了這個,但我很確定這將災難性地擴展。 但是,這可能是問題所固有的(我將'missing'
替換為''
)
length = 5
lsts = {tuple(): ['' for _ in range(length)]}
intr_lsts = []
sample = 'e1'
for _ in range(length):
new_lsts = {}
for filled, lst in lsts.items():
empty = set(range(length))-set(filled)
for e in empty:
new_filled = filled+tuple([e])
new_lst = list(lst)
new_lst[e] = str(sample)
if interrupt_criterion(new_lst):
intr_lsts.append(new_lst)
else:
new_lsts[new_filled] = new_lst
sample = 'e1' if sample=='e2' else 'e2'
lsts = new_lsts
out = list(lsts.values())+intr_lsts
#out = set(tuple(v) for v in out) # In case you want unique lists in output
print(out)
interupt_criterion
需要是一個列表(例如 lambda)上的可調用對象,但您當然可以更改它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.