How to use if and elif on checking variables?
AnsweredDear Python/Gurobi professionals:
Can you help meva question?
If I have two variable, AA[I,J] and BB[I,J,K] where I, J, K are index for demensions
How can I check if v.varName= AA[I,J] or v.varName=BB[I,J,K] so I can print as below?
for v in m.getVars():
if v.varName = AA ???:
print(AA"))
elif v.varName = BB ???:
print("BB")
Thank you very much
Robert
-
Hi Robert,
Assuming you want to look for variables whose names start with these letters, you can use the following:
for v in m.getVars():
if v.varName.startswith("AA"):
print("AA")
elif v.varName.startswith("BB"):
print("BB")However, it's usually possible to avoid searching for variables by name. This can be done by creating a variable from the object returned by the addVar() or addVars() method. For example,
aa = m.addVars(5, 5, name="AA")
creates 25 variables with names AA[0,0], AA[0,1], ..., AA[4,4]. In this example, aa is a tupledict object that contains these variables. This object is very useful, because it allows you direct access to the set of "AA" variables:
for v in aa:
print(v.varName)Thus, the aa tupledict object can be used to build constraints, retrieve variable values, etc. I hope this helps!
0 -
Hi Eli,
Thank you very much. It works!
Best
Robert
0 -
Hell Eli,
Can you please help me another question?
I have a code as below:
for v in m.getVars():
print('%s %g' % (v.varName, v.x))The varName is 3 by 2 dimension, so x is 3 by 2 dimension too
When I print, its output is like the following
A[1,1] 1
A[1,2] 3
A[2,1] 2
A[2,2] 4
A[3,1] 5
A[3,2] 3is there any way to print a line for each row, like as below:?
A[1,1] 1 A[1,2] 3
A[2,1] 2 A[2,2] 4
A[3,1] 5 A[3,2] 3Thank you very much
Robert
0 -
Hi Robert,
Assuming your decision variables were added in the following manner:
A = m.addVars(range(1,4), range(1,3), name="A")
you can print a line for each row as follows:
for i in range(1, 4):
alist = ["%s %g" % (v.varName, v.X) for v in A.select(i, '*')]
print("\t".join(alist))This code snippet uses the select() method of the tupledict object, as well as a Python list comprehension. An example of the output:
A[1,1] 1 A[1,2] 3
A[2,1] 2 A[2,2] 4
A[3,1] 5 A[3,2] 3I hope this helps!
Eli
0 -
Hi Eli,
Thank you very much for your help. It seems not easy to write the codes. I will give a try.
Sincerely,
Robert
0
Please sign in to leave a comment.
Comments
5 comments