Python: How to find out values of all feasible x under constraints.

Peter Otten __peter__ at web.de
Fri May 15 03:47:28 EDT 2015


Xiang Zhang wrote:

> I want to know how to find out values of all feasible x under constraints.
> 
> x = [x_1, x_2, x_3,..., x_10]
> 
> 
> constraints:
> x_i = 0,1,2,3 or 4,          where i=1,2,....10
> x_1 + x_2 + x_3 +...+x_10 <= 15

That are 5**10 == 9765625 candidates. That's still feasible to check using 
brute force.

> How to find out all the feasible solutions x (domain of x) using python,
> like [0,0,0,0,0,0,0,0,0,0], [1,1,1,1,1,1,1,1,1,1] etc ? What should be the
> code?
> 
> Any hint or help would be highly appreciated!

>>> solutions = [x for x in itertools.product(range(5), repeat=10) if sum(x) 
<= 15]
>>> len(solutions)
1556215

The first ten solutions:

>>> solutions[:10]
[(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0, 1), (0, 0, 0, 
0, 0, 0, 0, 0, 0, 2), (0, 0, 0, 0, 0, 0, 0, 0, 0, 3), (0, 0, 0, 0, 0, 0, 0, 
0, 0, 4), (0, 0, 0, 0, 0, 0, 0, 0, 1, 0), (0, 0, 0, 0, 0, 0, 0, 0, 1, 1), 
(0, 0, 0, 0, 0, 0, 0, 0, 1, 2), (0, 0, 0, 0, 0, 0, 0, 0, 1, 3), (0, 0, 0, 0, 
0, 0, 0, 0, 1, 4)]





More information about the Python-list mailing list