Reputation: 45
I need to solve the equation x + y + z = 1.
I need to generate all the possible combinations of x, y, z so the equation is correct
I want the values of x, y, z to be between 0.1 and 0.9 with jump of 0.1.
So the values are restricted to [0.1, 0.2, ..., 0.8, 0.9]
I have found this answer Finding all combinations of multiple variables summing to 1
However it applies to R not python.
It would be very helpfull if someone would enlighten me.
Upvotes: 0
Views: 1427
Reputation: 11929
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:
Upvotes: 2
Reputation: 6495
Avoiding nested loops directly in python:
import itertools
import numpy as np
x = y = z = [ i/10 for i in range(1,10)]
p = itertools.product(x,y,z)
combs = [e for e in p if np.sum(e) == 1]
Now combs
is a list of triplets (tuples) that sum to 1.
Upvotes: 0
Reputation: 27323
The most primitive solution would be a nested loop over all combinations:
def variable_combinations(sum_up_to=1):
for x in range(1, 10):
for y in range(1, 10):
for z in range(1, 10):
if x/10 + y/10 + z/10 == sum_up_to:
yield (x/10, y/10, z/10)
all_solutions = list(variable_combinations())
Upvotes: 0