Python itertools permutations with bound values

I want to find effective permutations of a vector that binds values.

For example, if perm_vector = [0,0,1,2] , I would like to get all combinations [0,0,1,2], [0,0,2,1], [0,1,2,0] as an output [0,0,1,2], [0,0,2,1], [0,1,2,0] , etc., but I do not want to get [0,0,1,2] twice, which will give the standard itertools.permutations(perm_vector) .

I tried the following, but it works very slowly when perm_vector grows in len:

 vectors_list = [] for it in itertools.permutations(perm_vector): vectors_list.append(list(it)) df_vectors_list = pd.DataFrame( vectors_list) df_gb = df_vectors_list.groupby(list(df_vectors_list.columns)) vectors_list = pd.DataFrame(df_gb.groups.keys()).T 

The question of a more general "accelerated" character, in fact. Most of the time is spent on creating permutations of long vectors - even without duplicity, creating permutations of a vector of 12 unique values ​​takes "infinity". Is it possible to call itertools iteratively, without accessing all the permutation data, but working on bundles?

+6
source share
2 answers

Try if perm_vector is small:

 import itertools as iter {x for x in iter.permutations(perm_vector)} 

This should give you unique values, because now it becomes a set, which by default removes duplicates.

If perm_vector is large, you can try rolling back:

 def permu(L, left, right, cache): for i in range(left, right): L[left], L[i] = L[i], L[left] L_tuple = tuple(L) if L_tuple not in cache: permu(L, left + 1, right, cache) L[left], L[i] = L[i], L[left] cache[L_tuple] = 0 cache = {} permu(perm_vector, 0, len(perm_vector), cache) cache.keys() 
+1
source

How about this:

 from collections import Counter def starter(l): cnt = Counter(l) res = [None] * len(l) return worker(cnt, res, len(l) - 1) def worker(cnt, res, n): if n < 0: yield tuple(res) else: for k in cnt.keys(): if cnt[k] != 0: cnt[k] = cnt[k] - 1 res[n] = k for r in worker(cnt, res, n - 1): yield r cnt[k] = cnt[k] + 1 
0
source

All Articles