[英]How to get all permutations of sizes {n, n-1,n-2, … 1} from list of size n efficiently?
我試圖從列表中找到與列表大小相同或更小的所有排列。
例如:
>>>allPermutations([a,b])
[[a,b], [b,a], [a], [b]]
這是我目前在python中的迭代代碼。 我不確定它目前的效率如何。
import itertools
def getAllPossibleSubSchedules( seq ):
fullSet = set()
curSet = set()
curSet.add(tuple(seq))
for i in reversed(range(1, len(seq) + 1)):
permutations = set()
for curTuple in curSet:
permutationsList = list(itertools.permutations(curTuple, i))
for permutation in permutationsList:
permutations.add(permutation)
curSet = set()
for permutation in permutations:
curSet.add(permutation)
fullSet.add(permutation)
return fullSet
我很確定算法會產生n的總和! 從1 - > n個排列變得非常快。 到目前為止,我已經創建了一種遞歸方式來執行它,這非常慢,因為它執行了許多重復操作。 我一直試圖通過迭代來做到這一點,但我無法弄清楚如何限制重復操作。 我正在使用python但psuedo-code也會幫助我很多。 任何幫助,將不勝感激。 提前致謝!
以下應該有效:
from itertools import permutations
def allPermutations(seq):
return (x for i in range(len(seq),0,-1) for x in permutations(seq, i))
例如:
>>> list(allPermutations('abc'))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('a',), ('b',), ('c',)]
也許迭代所有可能大小的列表的所有排列。 澄清:
def all_permutations(input_list):
for i in xrange(len(input_list)):
sublist = input_list[:i]
for variant in permutations(sublist):
yield variant
我很確定你的permutations.add()
和curSet.add()
以及fullSet.add()
調用將導致你的例程非常快地爬到停止狀態。 如果不斷更改數組的大小,分配的內存將“空間不足”,並且必須找到新位置。 這意味着整個數組被復制。 然后你添加另一個元素 - 沖洗並重復。
您需要計算所需的元素數量,並為此預先分配空間。 因此,如果你有5個元素,你需要為最終結果分配(5!+ 5 * 4!+ 10 * 3!+ 10 * 2!+ 5)x 5個元素 - 對於中間結果則少。 然后你填充這些數組,而不是改組內存塊; 它會讓事情變得更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.