英文:
Generate arrays with fixed number of non-zero elements
问题
- 长度固定为
N - 仅有
N中的M个元素为1, 剩余元素为0.
例如,N = 4 和 M = 2, 我们应该有
1: '0011'
2: '0101'
3: '0110'
4: '1001'
5: '1010'
6: '1100'
基本思想是从range(N)中选择M个元素,然后用1替换np.zeros(N)中相应的索引。然而,我只能通过在Python中使用多个for循环来实现这个想法,这样效率很低。我想问是否有任何直接的解决方案?提前感谢。
英文:
I have a question about how to generate all possible combinations of an array that satisfy the following condition:
- with fixed length
N - only
Melements amongNare1, 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.
答案1
得分: 1
以下是代码部分的翻译:
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.])]
英文:
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.])]
答案2
得分: 0
以下是代码部分的翻译:
# 生成一个包含所需数量的0和1的字符串,然后对其进行排列组合:
from itertools import permutations
n = 4 # 总长度
m = 2 # 1 的数量
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论