Generate arrays with fixed number of non-zero elements
Question:
I have a question about how to generate all possible combinations of an array that satisfy the following condition:
- with fixed length
N
- 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.
Answers:
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.])]
Generate a string with as many 0s and 1s as you need, then permutate it:
from itertools import permutations
n = 4
m = 2
item = []
for _ in range(m):
item.append("1")
for _ in range(n-m):
item.append("0")
perm = permutations(item)
for x in perm:
my_str = ""
for c in x:
my_str += c
print(my_str)
I have a question about how to generate all possible combinations of an array that satisfy the following condition:
- with fixed length
N
- only
M
elements amongN
are1
, and the rest elements are0
.
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.
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.])]
Generate a string with as many 0s and 1s as you need, then permutate it:
from itertools import permutations
n = 4
m = 2
item = []
for _ in range(m):
item.append("1")
for _ in range(n-m):
item.append("0")
perm = permutations(item)
for x in perm:
my_str = ""
for c in x:
my_str += c
print(my_str)