0

I want to generate a list of all permutations in an array that contains only 1s and 0s with no repetitions. I have used the code

import itertools 
import numpy as np 
L = 3
M = 2

list1=list(itertools.product([0,1],repeat=L+M-1))
list1_filtered=np.asarray(list(filter(lambda x: sum(x)==M,list1)))
print(list1_filtered)

and the output is

[[0 0 1 1]
 [0 1 0 1]
 [0 1 1 0]
 [1 0 0 1]
 [1 0 1 0]
 [1 1 0 0]]

Is there any way to make the generation faster (i.e. without using the filter operation to select only the array with total sum equal to M)?

Is it possible to create an iterative function f that starting from [0,0,1,1] gives recursively all the other rows? namely

f([0,0,1,1]) = [0,1,0,1], 
f([0,1,0,1]) = [0,1,1,0],
....
Galuoises
  • 2,630
  • 24
  • 30
  • I think my question is not a duplicate as here I want to generate permutations with no repetitions and list(itertools.permutations([0,0,1,1])) has to be filtered in any case – Galuoises Sep 12 '18 at 09:16
  • Moreover I am trying to find a recursive function that does the job, without using itertools – Galuoises Sep 12 '18 at 09:17
  • My answer [here](https://stackoverflow.com/a/31678111/4014959) shows how to efficiently produce permutations from lists containing repeated items. Also see the code I link on a comment on that answer. To get all permutations you need to sort the list first, since the permutations are produced in lexicographic order. – PM 2Ring Sep 12 '18 at 09:25
  • I haven't (yet) closed this question as a duplicate of the one I linked because the questions are rather different. However, my code does exactly what you want. So please let me know if that answer is adequate for your question. – PM 2Ring Sep 12 '18 at 09:34
  • 1
    Yes thank you. Your answer is what I was looking for. Indeed it is sufficient to use the next_perm function you wrote changing "Return False" and "Return True" with "Return a" – Galuoises Sep 12 '18 at 09:42

0 Answers0