You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

布尔数组全排列高效实现方案问询:替代低效Python代码

高效生成布尔数组的唯一排列

你的原代码效率低的核心问题是:permutations会生成所有重复排列(比如两个True交换位置的结果其实完全一样),再用set去重等于做了大量无用功,当数组变长时,计算量会爆炸式增长(比如n1=5、n2=5时,原方法要生成10!=3628800个排列,实际唯一排列只有C(10,5)=252个)。

更高效的实现思路

直接生成唯一位置组合:既然要放n1个True和n2个False,本质就是从总长度n1+n2的位置中选n1个位置放True,剩下的自动是False。用itertools.combinations可以直接生成这些不重复的位置组合,完全避免重复计算。

代码实现

方式1:逐个生成(内存友好,适合数量较大时)

from itertools import combinations
import numpy as np

n1 = 2
n2 = 3
total_len = n1 + n2

# 生成所有唯一排列
unique_perms = []
for true_positions in combinations(range(total_len), n1):
    arr = np.full(total_len, False)
    arr[list(true_positions)] = True
    unique_perms.append(arr)

# 查看结果
for perm in unique_perms:
    print(perm)

方式2:numpy批量生成(速度更快,适合中等规模)

from itertools import combinations
import numpy as np

n1 = 2
n2 = 3
total_len = n1 + n2

# 生成所有True的位置组合
true_positions = np.array(list(combinations(range(total_len), n1)))
# 批量构造布尔数组
unique_perms = np.zeros((len(true_positions), total_len), dtype=bool)
unique_perms[np.arange(len(true_positions))[:, None], true_positions] = True

# 查看结果
for perm in unique_perms:
    print(perm)

效率对比

  • 原方法时间复杂度:O((n1+n2)!),且需要额外的去重开销
  • 新方法时间复杂度:O(C(n1+n2, n1)),其中C是组合数,远小于阶乘

比如当n1=10、n2=10时,原方法要生成20!≈2.4e18个排列(完全不可能运行),而新方法只生成C(20,10)=184756个排列,瞬间就能完成。

内容的提问来源于stack exchange,提问作者Okapi575

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 04:55:17