# Select element of a list through the value of an operator

Here follow an occurence of a Fourier-Motzkin elimination.

fmf=[z<=4*x_1+ 3*x_2, x_1 + 3*x_2 <= 2100, 4*x_1+ 2*x_2<=1900, x_1<=200,x_2>=300, x_1 >=0,x_2 >=0]
fmf
fm_sol=solve_ineq(fmf,[x_1, x_2,z])
fm_sol


How can I select only the elements of the list generated by fm_sol where the operator for z is == ?

edit retag close merge delete

Sort by » oldest newest most voted Like this, for example:

sage: [sol for sol in fm_sol if next((ieq for ieq in sol if ieq.lhs() == z and ieq.operator() is operator.eq), None) is not None]
[[x_1 == 0, x_2 == 300, z == 900],
[x_1 == 0, x_2 == 700, z == 2100],
[x_1 == 200, x_2 == 300, z == 1700],
[x_1 == 200, x_2 == 550, z == 2450],
[x_1 == 150, x_2 == 650, z == 2550],
[x_2 == -2*x_1 + 950, z == -2*x_1 + 2850, 150 < x_1, x_1 < 200],
[x_2 == -1/3*x_1 + 700, z == 3*x_1 + 2100, 0 < x_1, x_1 < 150]]


Or in a more readable way, with a helper function:

def has_exact_equality(ieqns, variable):
for ieq in ieqns:
if ieq.lhs() == variable and ieq.operator() is operator.eq:
return True
return False


Then you can do:

sage: [sol for sol in fm_sol if has_exact_equality(sol, z)]
[[x_1 == 0, x_2 == 300, z == 900],
[x_1 == 0, x_2 == 700, z == 2100],
[x_1 == 200, x_2 == 300, z == 1700],
[x_1 == 200, x_2 == 550, z == 2450],
[x_1 == 150, x_2 == 650, z == 2550],
[x_2 == -2*x_1 + 950, z == -2*x_1 + 2850, 150 < x_1, x_1 < 200],
[x_2 == -1/3*x_1 + 700, z == 3*x_1 + 2100, 0 < x_1, x_1 < 150]]

more