<p>您可以使用类似<a href="https://www.coin-or.org/PuLP/" rel="nofollow">PuLP</a>的线性编程包。(注意,这还需要安装一个LP库,如<a href="http://www.gnu.org/software/glpk/" rel="nofollow">GLPK</a>)。</p>
<p>下面是如何使用它来解决您给出的示例:</p>
<pre><code>import pulp
prob = pulp.LpProblem("example", pulp.LpMinimize)
# Variable represent number of times device i is used
n1 = pulp.LpVariable("n1", 0, 5, cat="Integer")
n2 = pulp.LpVariable("n2", 0, 5, cat="Integer")
n3 = pulp.LpVariable("n3", 0, 5, cat="Integer")
n4 = pulp.LpVariable("n4", 0, 5, cat="Integer")
n5 = pulp.LpVariable("n5", 0, 5, cat="Integer")
# Device params
Device1=[8,8,4,4,200]
Device2=[16,0,16,0,250]
Device3=[8,0,4,4,300]
Device4=[16,8,4,4,300]
Device5=[8,8,2,2,150]
# The objective function that we want to minimize: the total cost
prob += n1 * Device1[-1] + n2 * Device2[-1] + n3 * Device3[-1] + n4 * Device4[-1] + n5 * Device5[-1]
# Constraint that we use no more than 5 devices
prob += n1 + n2 + n3 + n4 + n5 <= 5
Target = [24, 12, 16, 8]
# Constraint that the total I/O for all devices exceeds the target
for i in range(4):
prob += n1 * Device1[i] + n2 * Device2[i] + n3 * Device3[i] + n4 * Device4[i] + n5 * Device5[i] >= Target[i]
# Actually solve the problem, this calls GLPK so you need it installed
pulp.GLPK().solve(prob)
# Print out the results
for v in prob.variables():
print v.name, "=", v.varValue
</code></pre>
<p>运行这个非常快,我得到n1=2和n2=1,其他的都是0。</p>