-2

I'm using Python to solve an integer program using Gurobi. After defining all variables and constraints, I'm getting the following answers for my integer variable x[i,j].

x(0,0) 0.0
x(0,1) 0.0
x(0,2) 1.0
x(0,3) 1.0
x(1,0) 0.0
x(1,1) 0.0
x(1,2) 0.0
x(1,3) 0.0
x(2,0) 0.0
x(2,1) 0.0
x(2,2) 0.0
x(2,3) 0.0
x(3,0) 0.0
x(3,1) 0.0
x(3,2) 0.0
x(3,3) 0.0

So, in the next step, I need to pass all i,j s for which x[i,j]=1 to a set called S. I'm using the following code for this.

S=[]
if x[i,j]== 1:
  S.append(i)
  S.append(j)
  print(S)

This prints S=[0,3]. But the correct one should be S=[0,2,3]. Can someone please help me to identify the mistake here?

ccc
  • 574
  • 2
  • 9
  • 22

1 Answers1

1

First thing, the code provided is not complete so I can only speculate what you could have done and give suggestions based on it.

I believe that you have written a for loop and in that S = [] is getting initialised all the time.

Thus, your code though almost correct still gives only the last matching solution.

What I would have done would be following:

S = []

<here goes code for some for loop to consider all the x[i,j] values>
    if x[i,j] == 1:
        if not S.index[i]>-1:
            S.append[i]
        if not S.index[j]>-1:
            S.append[j]
return S

This pseudo-code based program should give you the correct solution :)

anugrah
  • 187
  • 1
  • 1
  • 10
  • 2
    This is not very efficient, better to just use `S = set()` and `s.update((i, j))`. Set's automatically handle duplicate entries. Note: `if i not in S` would be the more appropriate condition. – AChampion Jul 13 '17 at 03:31