Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate arrays with fixed number of non-zero elements

I have a question about how to generate all possible combinations of an array that satisfy the following condition:

  1. with fixed length N
  2. only M elements among N are 1, and the rest elements are 0.

For example, N = 4 and M = 2, we shall have

1: '0011'
2: '0101'
3: '0110'
4: '1001'
5: '1010'
6: '1100'

The basic idea is to pick up M elements from range(N) and replace the corresponding indices in np.zeros(N) with 1. However, I can only realize this idea by using several for-loops in python, which is inefficient. I’d like to ask whether there is any straightforward solution? Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way is to use itertools to get all possible combinations of the locations of ones and fill N-zero arrays with these ones.

import itertools
import numpy as np

N = 4
M = 2

combs = list(itertools.combinations(range(N), M))
result = [np.zeros(N) for _ in range(len(combs))]

for i, comb in enumerate(combs):
    for j in comb:
        result[i][j] = 1
print(result)
[array([1., 1., 0., 0.]), array([1., 0., 1., 0.]), array([1., 0., 0., 1.]), array([0., 1., 1., 0.]), array([0., 1., 0., 1.]), array([0., 0., 1., 1.])]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading