Search code examples
pythonequation-solving

Python: Positive integral solutions for Linear Equation


I want to find all POSITIVE INTEGRAL solutions for a,b for this simple, toy linear equation: a + 2b = 5 and for which the solutions are:

a|5|3|1|
b|0|1|2|

I've tried a few things after going some posts here and the "python-constraint" module was helpful, for example:

from constraint import *
problem = Problem()
problem.addVariables(['a', 'b'], range(10))
problem.addConstraint(lambda a, b: 5 == 2*b + a , ('a', 'b'))
solutions = problem.getSolutions()
print(solutions)

Prints out the solutions as follows:

[{'a': 5, 'b': 0}, {'a': 3, 'b': 1}, {'a': 1, 'b': 2}]

I've two questions: 1. In real example I know the bounds of the variables a,b etc. Can I separately input the bounds or domains of both a and b to problem.addVariables() or do I have to use problem.addVariable() instead ?

Secondly, is their any other way of doing this simply in Python like using the 'sympy' or 'pulp' or any other? I'm not sure how to get the extract solutions from sympy's solve() output:

import sympy
a,b = symbols('a b', integer=True)
solve( a*1 + b*2 - 5, [a,b])

Which gives me the following output:

[(5 - 2*b, b)]

Thanks


Solution

    • addVariables in python-constraints supports one domain for all variables. If you want to specify the domain for each variable separately, use addVariable. For example,

      problem.addVariable("a", [1, 2, 3])

    • I'm not sure what you mean by "any other way of doing this simply in Python", but sympy already gives you an answer to your problem.

      The problem you passed to sympy's solve is unbounded, so it cannot give you an infinite number of solutions. Instead it returns a parameterized set of solutions. If you iterate over different values of b [(5 - 2*b, b)], you can generate solutions.