Ask Your Question
1

Select element of a list through the value of an operator

asked 2021-10-30 17:37:22 +0100

CyrilleP gravatar image

updated 2021-10-30 17:40:24 +0100

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-10-30 17:56:15 +0100

rburing gravatar image

updated 2021-10-30 17:59:49 +0100

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]]
edit flag offensive delete link more

Comments

Thanks ! Exactly what I was unable to code.

CyrilleP gravatar imageCyrilleP ( 2021-10-30 18:20:08 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-10-30 17:37:22 +0100

Seen: 495 times

Last updated: Oct 30 '21