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

如何高效获取0-5列表中满足a²+b²<12的全部两数组合

优化解决方案

原有实现的核心问题:

  • 依赖随机采样覆盖所有组合,无法保证100%覆盖所有符合条件的结果,且执行次数无意义(factorial(5)=120次循环远大于所有可能的两数组合总数36)
  • 用列表存储已遍历的组合,in查询的时间复杂度为O(n),额外增加了不必要的性能开销
  • 手动维护正反序对的逻辑容易出错,可读性差

高效实现方案

因为你的输入范围是固定的0~5,所有两数组合总量极小,直接穷举所有可能是最优选择,性能和可读性都拉满。

场景1:需要返回有序对(即(a,b)和(b,a)视为不同结果)

可以直接用双重循环或者itertools.product实现:

# 无第三方依赖版本
nodes = range(6)
res = []
for a in nodes:
    for b in nodes:
        if a ** 2 + b ** 2 < 12:
            res.append((a, b))
print(res)
# 用itertools简化写法
from itertools import product
nodes = range(6)
res = [pair for pair in product(nodes, repeat=2) if pair[0]**2 + pair[1]**2 < 12]

输出结果为:
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1)]

场景2:需要返回无序对(即(a,b)和(b,a)视为同一结果,仅保留一份)

可以限定a <= b避免重复,或者直接用itertools.combinations_with_replacement实现:

from itertools import combinations_with_replacement
nodes = range(6)
res = [pair for pair in combinations_with_replacement(nodes, 2) if pair[0]**2 + pair[1]**2 < 12]

输出结果为:
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 2)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:36:03