Get all permutations of a numpy array

I have a numpy array [0, 1, 1, 2, 2, 0, 1, ...] that contains only the numbers 0-k. I would like to create a new array containing n possible 0-k permutation arrays. A small example with k = 2 and n = 6:

a = [0, 1, 0, 2] permute(a) result = [[0, 1, 0, 2] [0, 2, 0, 1] [1, 0, 1, 2] [2, 1, 2, 0] [1, 2, 1, 0] [2, 0, 2, 1]] 

Does anyone have any ideas / solutions on how to achieve this?

+6
source share
2 answers

Your a is what combinators call a multiset. The sympy library has various routines for working with them.

 >>> from sympy.utilities.iterables import multiset_permutations >>> import numpy as np >>> a = np.array([0, 1, 0, 2]) >>> for p in multiset_permutations(a): ... p ... [0, 0, 1, 2] [0, 0, 2, 1] [0, 1, 0, 2] [0, 1, 2, 0] [0, 2, 0, 1] [0, 2, 1, 0] [1, 0, 0, 2] [1, 0, 2, 0] [1, 2, 0, 0] [2, 0, 0, 1] [2, 0, 1, 0] [2, 1, 0, 0] 
+12
source

if your permutations fit into memory, you can save them in set and thus only get distinguishable permutations.

 from itertools import permutations a = [0, 1, 0, 2] perms = set() for perm in permutations(a): perms.add(perm) print(perms) 

or - as shown by John Coleman - on one line:

 perms = set(permutations(a)) 
+5
source

Source: https://habr.com/ru/post/1013261/


All Articles