Examining variables with nonzero values in a solution¶
Documents ways to examine nonzero variables in a solution: for-loop, lambda expression, function.
To examine the nonzero values of variables in a solution, the Python API of CPLEX offers several alternatives.
You can enter a for-loop interactively to print the solution, like this:
>>> for i, x in enumerate(c.solution.get_values()):
... if (x!=0): #leading spaces for indention
... print "Solution value of ", c.variables.get_names(i), \
... " is ", x
Solution value of Open(1) is 1.0
Solution value of Open(2) is 1.0 ...
You can enter a for-loop interactively to print the solution, like this: >>> for i, x in enumerate(c.solution.get_values()): … if (x!=0): #leading spaces for indention … print “Solution value of “, c.variables.get_names(i), … “ is “, x Solution value of Open(1) is 1.0 Solution value of Open(2) is 1.0 …
You can enter a lambda expression interactively to print the solution, like this:
>>> print zip([1,2],[3,4]); # built-in function zip
[(1, 3), (2, 4)]
>>> print filter(lambda x:x[1]!=0,
zip(c.variables.get_names(),c.solution.get_values()))
[('Open(1)', 1.0), ('Open(2)', 1.0), ...
You can enter a lambda expression interactively to print the solution, like this: >>> print zip([1,2],[3,4]); # built-in function zip [(1, 3), (2, 4)] >>> print filter(lambda x:x[1]!=0, zip(c.variables.get_names(),c.solution.get_values())) [(‘Open(1)’, 1.0), (‘Open(2)’, 1.0), …
You can write a reusable function to print the solution, like this:
>>> def display_solution_nonzero_values (c):
... for i, x in enumerate(c.solution.get_values()):
... if (x!=0):
... print "Solution value of ",c.variables.get_names(i),\
... " is ", x
>>> display_solution_nonzero_values(c)
Solution value of Open(1) is 1.0
Solution value of Open(2) is 1.0 ...
You can write a reusable function to print the solution, like this: >>> def display_solution_nonzero_values (c): … for i, x in enumerate(c.solution.get_values()): … if (x!=0): … print “Solution value of “,c.variables.get_names(i),… “ is “, x >>> display_solution_nonzero_values(c) Solution value of Open(1) is 1.0 Solution value of Open(2) is 1.0 …