"int'对象不可下标" [英] "int 'object is not subscriptable"
问题描述
我开始学习GEKKO.现在,我正在解决一个要学习的knapsak问题,但是这次我得到了错误"int'对象不可下标".你能看一下这段代码吗?问题的根源是什么?如何定义1.10矩阵?
i'm starting to learn GEKKO. Now, I am solving a knapsak problem to learn, but this time I get the error "int 'object is not subscriptable". can you look at this code? what is the source of the problem How should I define the 1.10 matrices?
from gekko import GEKKO
import numpy as np
m = GEKKO(remote=False)
x = m.Var((10),lb=0,ub=1,integer=True)
#x = m.Array(m.Var,(1,10),lb=0,ub=1,integer=True)
v=np.array([2, 2, 7, 8, 2, 1, 7, 9, 4, 10])
w=np.array([2, 2, 2, 2, 2, 1, 6, 7, 3, 3])
capacity=16
for j in range(10):
m.Maximize(v[j]*x[j])
for i in range(10):
m.Equation(m.sum(x[i]*w[i])<=capacity)
m.options.solver = 1
m.solve()
#print('Objective Function: ' + str(m.options.objfcnval))
print(x)
我的第二个问题是MATLAB中有一个名为"showproblem()"的函数. GEKKO是否具有此功能?
My second question is that there is a function called "showproblem ()" in MATLAB. Does GEKKO have this function?
感谢您的帮助. 根据答案的新问题. 我可以在这里写这种风格(不行,如果可以的话,请写工作风格)(我想写这种风格,因为我认为这种风格更容易理解.)
thanks for help. new question that according to answer. can i write here this style(that doesnt work, if i can do it, please write working style)(i want to write this style, because i think this style is easier to understand.),
for i in range(10):
xw = x[i]*w[i]
m.Equation(m.sum(xw)<=capacity)
代替这个.
xw = [x[i]*w[i] for i in range(10)]
m.Equation(m.sum(xw)<=capacity)
推荐答案
此处是修改版本,可以解决gekko中的混合整数问题.
Here is a modified version that solves the mixed integer problem in gekko.
from gekko import GEKKO
import numpy as np
m = GEKKO(remote=False)
x = m.Array(m.Var,10,lb=0,ub=1,integer=True)
v=np.array([2, 2, 7, 8, 2, 1, 7, 9, 4, 10])
w=np.array([2, 2, 2, 2, 2, 1, 6, 7, 3, 3])
capacity=16
for j in range(10):
m.Maximize(v[j]*x[j])
xw = [x[i]*w[i] for i in range(10)]
m.Equation(m.sum(xw)<=capacity)
m.options.solver = 1
m.solve()
print('Objective Function: ' + str(-m.options.objfcnval))
print(x)
您的问题表述很接近.您只需要定义用于形成容量约束的列表xw
.
如果要使用循环而不是列表理解,则建议使用以下内容代替xw = [x[i]*w[i] for i in range(10)]
.
Your problem formulation was close. You just needed to define a list xw
that you use to form the capacity constraint.
If you want to use a loop instead of a list comprehension then I recommend the following instead of xw = [x[i]*w[i] for i in range(10)]
.
xw = []
for i in range(10):
xw.append(x[i]*w[i])
这篇关于"int'对象不可下标"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!