简体   繁体   English

约束库的 problem.getSolutions() 不产生任何解决方案

[英]problem.getSolutions() of constraint library yielding no solutions

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.我正在尝试使用 Python 中的“约束”库来解决一个小的约束问题。代码如下,但解决方案是空的。 I was expecting a solution for Km * wt_Km (1 *42).我期待 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)

Move the problem = Problem() up to be after wt_Mx initialization, does that fix it?problem = Problem()移到 wt_Mx 初始化之后,这样可以解决问题吗?

Edit 2: I found the solution to your problem, at least it solves correctly on Python 3.6.15 on my Ubuntu 20.04LTS.编辑 2:我找到了您问题的解决方案,至少它在我的 Ubuntu 20.04LTS 上的 Python 3.6.15 上正确解决了。 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: 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而 output 是

[{'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.我尝试使用 Python 3.10、3.6、3.5 和 2.7,但都没有用。 I couldn't install Python 3.4 to try it on that.我无法安装 Python 3.4 来尝试它。

I think your problem (and the problem above) should yield a solution, but somehow they don't.我认为你的问题(和上面的问题)应该产生一个解决方案,但不知何故他们没有。

I am confused.我很困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM