Python: how to find out values of all feasible x under constraints -
i writing code using python now.
i want know how find out values of feasible x under constraints.
x = [x_1, x_2, x_3,…, x_10]
constraints:
x_i = 0, 1, 2, 3 or 4, i= 1, 2, ….10 x_1 + x_2 + x_3 +...+ x_10 <= 15
how find out feasible solutions x (domain of x) using python, [0,0,0,0,0,0,0,0,0,0]
, [1,1,1,1,1,1,1,1,1,1]
etc ? should code?
any hint or highly appreciated!
sincerely,
eddie
if want use naive method of iterating through possibilities, can use itertools.product. can give possible solutions:
>>> possibles = itertools.product(range(5), repeat=10)
now can filter out tuples sum greater 15 using simple comprehension:
>>> solutions = [x x in possibles if sum(x) <= 15]
or in 1 line:
>>> solutions = [x x in itertools.product(range(5), repeat=10) if sum(x) <= 15]
Comments
Post a Comment