I'm trying to use Sympy to solve 0 < x + y <= 4 in the case where both x and y are positive integers or 0, in the hopes to have it return a list of tuples that solves the inequality.
import sympy as sp
# Assign variables
x, y = sp.symbols('x y', natural0 = True)
# Define the inequalities
ineq1 = sp.And(0 < x + y, x + y <= 4)
ineq2 = x >= 0
ineq3 = y >= 0
# Solve the inequality
result = sp.solve([ineq1, ineq2, ineq3], [x,y])
Expected result:
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (4, 0)]
Solve()
can not do that. You can just do it manually:
import sympy as sp
x, y = sp.symbols('x y')
ineq1 = sp.And(0 < x + y, x + y <= 4)
ineq2 = x >= 0
ineq3 = y >= 0
result = []
for xi in range(5):
for yi in range(5):
A = ineq1.subs({x: xi, y: yi})
B = ineq2.subs({x: xi, y: yi})
C = ineq3.subs({x: xi, y: yi})
if A and B and C:
result.append((xi, yi))
print(result)
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (4, 0)]