首页 > 解决方案 > 如何生成总和为 1 的三个变量的所有可能组合

问题描述

我需要解方程 x + y + z = 1。

我需要生成 x、y、z 的所有可能组合,所以方程是正确的

我希望 x、y、z 的值介于 0.1 和 0.9 之间,跳跃为 0.1。

所以值被限制为 [0.1, 0.2, ..., 0.8, 0.9]

我找到了这个答案找到多个变量的所有组合总和为 1

但是它适用于 R 而不是 python。

如果有人能启发我,那将非常有帮助。

标签: python

解决方案


Instead of a nested triple loop, you can consider generating all triplets

triplets = [(x/10.0, y/10.0, (10-x-y)/10.0) for x in range(1,9) for y in range(1,10-x)]

where each triplet (a,b,c) represents the possible values to be assigned to x, y, and z.

Note that I'm multiplying by 10 for then dividing when building the triplets to avoid rounding errors that might come up when doing directly:

if x/10 + y/10 + z/10 == 1:

推荐阅读