問題: 如何指定我的itertools.permutations對象,以便它只包含在列表中給出的一個開頭的排列? (Python 3.5)如何指定只允許某些第一組合的itertools排列?
故事: 我有一個難題,有36個益智元素,所以理論上4e + 41的可能性。如果我用itertools.permutations檢查它,它會永遠計算。因此,我嘗試檢查首先放置哪些方塊,然後只查找第一個地方的第二個地方,這是可能的。
例如塊2不適合在第一個地方,然後和itertools.permutations(MYLIST,2)不應該再包含像(2,1)(2,2)(2,3)等等
mylist = [0,1,2,3] # ..,34,35 - contains all puzzle blocks
begin = [(1,2),(1,3)] # this is the list of possible first blocks, so itertools should only give me combinations, that begin with one of this possibillities
combs = itertools.permutations(mylist,3) # --- THIS IS THE LINE OF THE QUESTION ---
組合在現在,我這樣做使用:
for thisposs in combs:
if thisposs[0:2] in begin:
checkblock(thisposs) # check if thisposs is a combination that solves the puzzle
但這種方式的for循環仍爆炸。我想指定迭代工具對象,以便它不具有所有的可能性,但只有那些與東西是數組/元組/列表內開始:
begin = [(1,2),(1,3)] # only one of these should be allowed in first two slots
該數組我每次增加時間重新計算一個準確的步驟,所以在優化過程中,可能需要像值:
begin = [1,3,4,5,6] # after permutations(mylist,1) - still a lot beginnings are possible
begin = [(1,6),(1,7),(5,1),(6,7)] # after permutations(mylist,2) - some combinations didn't work further
begin = [(5,1,2),(5,1,6),(5,1,7)] # after permutations(mylist,3) - the solution can for sure only begin with 5-2-???
# and so on
每次我做了一個「精度一步」,我提出一個新的itertools對象與
combs = itertools.permutations(mylist,n+1)
所以我的問題是:如何指定我的itertools.permutations對象,以便它只包含列表中給出的一個開始的排列?
不要使用'itertools.permutations'。自己實施回溯搜索。 – user2357112
是的,這絕對沒有內置的支持。 –