-1

I have created a numpy array

a=np.array([1,2,3])
a
>>> array([1, 2, 3])

I would like to change the positions of the elements.

My expected output should only consists of these three patterns

[array([1, 2, 3]),
 array([2, 3, 1]),
 array([1, 3, 2])]

I tried with permutation library like below

b=[]
for i in range(3):
    b.append(np.random.permutation(a)

Actual output:

[array([1, 3, 2]), 
array([1, 3, 2]), 
array([1, 2, 3])]

But I'm getting repeated values some times!!

Ideas are welcome!!

Thanks in Advance!!

  • How did you get your expected output? it includes only 3 of 6 different permutations of your array. Also, in your for loop, you create a random permutation. There is always a chance it repeats. – Ehsan Apr 27 '20 at 18:10
  • Does this answer your question? [How to generate all permutations of a list?](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list) – Joseph Wood Apr 27 '20 at 20:06

2 Answers2

0

If you want no repetitions try the builtin itertools.permutations() utility. Without any arguments it will return all possible permutations:

>>> import itertools
>>> list(itertools.permutations([1,2,3]))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

(Noting a 3-element list has 6 permutations)

Or with numpy arrays:

>>> import numpy as np
>>> [np.array(a) for a in (itertools.permutations([1,2,3]))]
[array([1, 2, 3]), array([1, 3, 2]), array([2, 1, 3]), array([2, 3, 1]), array([3, 1, 2]), array([3, 2, 1])]
AbbeGijly
  • 1,191
  • 1
  • 4
  • 5
0

If I understand you correctly, you want to randomly pick 3 of all possible permutations (here 6 for a 3-element array). You can create an array of all possible permutations and then use np.random.choice to randomly pick 3 of them. You need to set replace flag to False to avoid repetitions:

import itertools

a = np.array(list(itertools.permutations([1,2,3])))
a = a[np.random.choice(a.shape[0], 3, replace=False), :]

sample output:

[[1 3 2]
 [2 1 3]
 [1 2 3]]
Ehsan
  • 12,072
  • 2
  • 20
  • 33