生成具有固定数量非零元素的数组。

huangapple go评论74阅读模式
英文:

Generate arrays with fixed number of non-zero elements

问题

  1. 长度固定为N
  2. 仅有N中的M个元素为1, 剩余元素为0.

例如,N = 4M = 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:

  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.

答案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)

huangapple
  • 本文由 发表于 2023年2月6日 05:12:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定