maow
maow

Reputation: 2887

How to restrict sympy FiniteSet containing symbol

I am fairly new to sympy. I tried to solve a system of linear equations with linsolve(). This yields a solution which can be reproduced with the two following lines.

d = symbols("d")
solution = sets.FiniteSet((d + 1, -d + 4, -d + 5, d))

My solution obeys the restriction, that all four values must be positive integers. This happens for d = 0, 1, 2, 3, 4.

I was able to evaluate solution at a fixed d (e. g. d = 0) with

solution.subs({d : 0})

What I would like to have restrict the set of solutions to the valid ones automatically. Mathematically that amounts to the intersection with \mathbb{N^0}^4. In practice I would like to get an output like from

for d_fixed in range(5):
    solution.subs({d : d_fixed})

i. e.

{(1, 4, 5, 0)}
{(2, 3, 4, 1)}
{(3, 2, 3, 2)}
{(4, 1, 2, 3)}
{(5, 0, 1, 4)}

How can I do this?

Upvotes: 3

Views: 467

Answers (1)

Bill Bell
Bill Bell

Reputation: 21643

I think something along these lines will do it, with a little extra magic from you.

>>> from sympy import *
>>> var('d')
d
>>> solution = sets.FiniteSet((d+1,-d+4,-d+5,d))
>>> list(list(solution)[0])
[d + 1, -d + 4, -d + 5, d]
>>> from sympy.solvers.inequalities import reduce_inequalities
>>> reduce_inequalities([0<=d + 1, 0<=-d + 4, 0<=-d + 5, 0<=d],[d])
And(0 <= d, d <= 4)

I am indebted to https://stackoverflow.com/users/1879010/dietrich for a comment that I have been forgetting to read until I saw your question.

Upvotes: 3

Related Questions