python - 如何获得所有可能的约束组合?

标签 python

<分区>

我需要从具有以下约束的列表中获取所有可能的 5 种组合:

  • 组合必须包括重复。
  • 所有数字的总和等于 1。

到目前为止,这是我的代码:

    number = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
    comb = [c for c in itertools.product(number, repeat=5) if  c[0] + c[1] + c[2] + c[3] + c[4] == 1]
    for cb in comp:
        print(cb)

我似乎没有得到所有可能的组合。例如,输出的第一行是

(0.1, 0.1, 0.1, 0.1, 0.6)

但不包括以下任何一项

(0.6, 0.1, 0.1, 0.1, 0.1)
(0.1, 0.6, 0.1, 0.1, 0.1)
(0.1, 0.1, 0.6, 0.1, 0.1)
(0.1, 0.1, 0.1, 0.6, 0.1)

等等。我也尝试了不同的方法

itertools.combinations_with_replacement
itertools.permutations

最佳答案

itertools.product函数确实输出你想要的,问题在于检查 float 的相等性,为此你可以使用 math.isclose :

from itertools import product
import math
comb = [c for c in product(number, repeat=5) if math.isclose(sum(c), 1.0)]

关于python - 如何获得所有可能的约束组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54205314/

相关文章:

python - 如何限制Qlineedit输入?

python - 获取 .py 源文件的位置

python - F2PY - 从子程序访问模块参数

python - python 中的元组排序

python - 使用 python 运行 cmd 命令(停止/启动服务)

python - 属性错误 : 'QWheelEvent' object has no attribute 'delta'

python lambda if/else 条件失败 : 'int' and 'function' conflicts

python - Psycopg2 中的 `TypeError: argument 2 must be a connection, cursor or None`

python - RobotFramework - 通过 Open Browser 关键字添加 chrome 扩展

python - 如何读取大文件(套接字编程和python)?