Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all permutations of a numpy array

Tags:

python

numpy

I have a numpy array [0, 1, 1, 2, 2, 0, 1, ...] which only contains the numbers 0-k. I would like to create a new array that contains the n possible arrays of permutations of 0-k. 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 as to how one could achieve this?

like image 932
MBrown Avatar asked Dec 18 '16 15:12

MBrown


People also ask

How do you find all permutations?

To calculate the number of permutations, take the number of possibilities for each event and then multiply that number by itself X times, where X equals the number of events in the sequence. For example, with four-digit PINs, each digit can range from 0 to 9, giving us 10 possibilities for each digit.

What is NumPy permutation?

Overview. The Random module in NumPy helps make permutations of elements of an array. Permutation refers to the arrangement of elements in an array. For example, [3, 1, 2] and [1, 3, 2] are permutations of the array elements in [1, 2, 3] and vice versa.

How do you find all the permutations of a string in Python?

To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.


2 Answers

Your a is what combinatorists 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]
like image 79
Bill Bell Avatar answered Oct 06 '22 19:10

Bill Bell


if your permutations fit in the memory, you could store them in a set and thus only get the distinguishable permutations.

from itertools import permutations

a = [0, 1, 0, 2]

perms = set(permutations(a))
like image 34
hiro protagonist Avatar answered Oct 06 '22 18:10

hiro protagonist