Skip to main content
 首页 » 编程设计

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

2025年05月04日12unruledboy

<分区>

我需要从具有以下约束的列表中获取所有可能的 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