problem.getSolutions() of constraint library yielding no solutions

Question:

I’m trying to solve a small constraint problem using the "constraint" library in Python.
The code is as follows but the solutions is empty. I was expecting a solution for Km * wt_Km (1 *42). Can somebody help in solving this?
Thanks

from constraint import *

wt_Nd = 1
wt_Qd = 1
wt_Km = 42
wt_Ka = 14
wt_Mx = 16

problem = Problem()
problem.addVariable('Nd', range(1))
problem.addVariable('Qd', range(2))
problem.addVariable('Ka', range(2))
problem.addVariable('Km', range(2))
problem.addVariable('Mx', range(1))

value_diff = 42


problem.addConstraint(lambda Nd,Qd,Km,Ka,Mx: value_diff == Nd * wt_Nd +
                                                           Qd * wt_Qd + 
                                                           Km * wt_Km +
                                                           Ka * wt_Ka +
                                                           Mx * wt_Mx ,
                                                          ('Nd','Qd','Km', 'Ka', 'Mx') )
solutions = problem.getSolutions()
print(solutions)
Asked By: The August

||

Answers:

Move the problem = Problem() up to be after wt_Mx initialization, does that fix it?

Edit 2: I found the solution to your problem, at least it solves correctly on Python 3.6.15 on my Ubuntu 20.04LTS. I still don’t get the answer from the example, which is odd.

In your answer, change

Nd + wt_Nd +

to

Nd * wt_Nd +

output:

[{'Mx': 0, 'Nd': 0, 'Ka': 0, 'Km': 1, 'Qd': 0}

Edit: I am starting to think that there is a problem with the library.
I copied the example from here (I added prints):

from constraint import *

problem = Problem()
problem.addVariable("a", [1, 2, 3])
problem.addVariable("b", [4, 5, 6])
print(problem.getSolutions())

problem.addConstraint(lambda a, b: a * 2 == ("a", "b"))
print(problem.getSolutions())

And the output was

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

I tried with Python 3.10, 3.6, 3.5 and 2.7, none of them worked. I couldn’t install Python 3.4 to try it on that.

I think your problem (and the problem above) should yield a solution, but somehow they don’t.

I am confused.

Answered By: jolammi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.