-2

I am writing a linear program in python gurobi and I am trying to create some constraints only including a multiplication of the elements of two lists but excluding the zeros. More specifically: A is a list that contains only positive or zero elements, B is a list with binary variables demonstrating the positions where there are zeros in A list, for example:

A=[1,2,0,3,0]
B=[1,1,0,1,0]

I want to add some constraints including only the A[x]*B[x] but not the zeros.

Anybody has any idea how this could be done?

Dadep
  • 2,796
  • 5
  • 27
  • 40
Thomas
  • 31
  • 1
  • 7
  • 1
    something like `A = [a for a in A if a]` ? not sure. what's your input/expected output? – Jean-François Fabre Mar 24 '17 at 12:33
  • Do you actually want to remove the zeros or just not use them when running calculations like in your example above? – elPastor Mar 24 '17 at 12:40
  • Jean-Frenacois thanks for the advice, but this does not work. I am writing in gurobi meaning that an if statement is not possible. pshep i just want to not use them when creating other constraints, completely ignore them. I will iterate through all elements of those two lists and i just want to create the constraints only for the items that are non zero – Thomas Mar 24 '17 at 12:51
  • 1
    The practical formulation depends on the details. Usually we can use some implications or some big-M formulation. – Erwin Kalvelagen Mar 24 '17 at 14:40
  • 1
    You should clarify what are data and what are decision variables; you don't need a constraint for the obvious relationship of x[i] = 1 if and only if a[i] > 0. – Greg Glockner Mar 24 '17 at 16:00
  • Yes, more specifically: A is a decision variable. B is a binary(again decision variable) that depends only on whether A[i] is 0 or >0. Therefore, i need to create constraints using B[i] but only for i which are not zero. that is only because in the constraints i have to formulate a minimization of a variable, but only take the minimum from the non zero B[i], else i will always get 0 as the min(B[i]*C[i]), where C[i] is just data. – Thomas Mar 26 '17 at 13:16

3 Answers3

3

This will do the job:

import numpy as np
A=np.array([1,2,0,3,0])
B=np.array([1,1,0,1,0])
C=A[B>0]

The C is array([1, 2, 3])

Also, similarly to what @Jean-François Fabre suggested, you can just do

import numpy as np
A=np.array([1,2,0,3,0])
C=A[A!=0]
Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
0

If you just want to remove 0 from the list of int you can do :

A=[1,2,3,0,4,3,0,0,0,1]
C=[i for i in A if i!=0]

output :

C=[1,2,3,4,3,1]
Dadep
  • 2,796
  • 5
  • 27
  • 40
0

This will work.

A = [1, 2, 0, 3, 0]
B = [1, 1, 0, 1, 0]
mul = [a*b for a,b in zip(A,B) if a != 0 and b !=0]
print mul
Sudhanshu Dev
  • 360
  • 3
  • 9
  • thanks for the answer but i am writing in gurobi, which means if or != is not allowed :). Thanks again though – Thomas Mar 24 '17 at 13:08