0

I used this example here if/else in a list comprehension for list comprehension with if-else to create a constraint for the sum .

This is the piece of code that triggers the error

    for j in range(1, m+1):
        solver.Add(solver.Sum([0 if c[i][j]==0 else x[i, j] for i in range(1, n+1)]) <= 1)

x is a dict defined earlier and c[i][j] is a boolean that is 1 when (i,j) is in the permitted. But when (i,j) is in permitted x[i,j] holds a variable in ortools . So what I am saying is that I want for this particular j to sum x[i,j]'s , if x[i,j] exists then ok if it does not then just add 0 .

    c = [[0]*(m+1)]*(n+1)
    for (i,j) in permitted:
        c[i][j]=1

    x = {}
    for (i,j) in permittted:
            x[i, j] = solver.IntVar(0, 1, '')
Laurent Perron
  • 8,594
  • 1
  • 8
  • 22
tonythestark
  • 519
  • 4
  • 15
  • Is `(1, 1)` present in `x`? There is no way for us to know. According to the error message, it isn't. It's best if you try to create a [SSCCE](http://sscce.org/). – Lev Levitsky May 23 '22 at 14:49
  • @LevLevitsky c[i][j] is a boolean that checks this (I will include it i the description of my question) – tonythestark May 23 '22 at 15:01

1 Answers1

2

There is a problem with how your boolean list is defined. Consider this:

In [1]: c = [[0] * 2] * 3

In [2]: c
Out[2]: [[0, 0], [0, 0], [0, 0]]

In [3]: c[1][1] = 1

In [4]: c
Out[4]: [[0, 1], [0, 1], [0, 1]]

In c, you actually have the same inner list repeated, so assigning a single value is reflected in each copy. Hence your checks for c[i][j] == 0 may not produce the results you expected.

Try changing the definition of c to:

c = [[0] * (m + 1) for _ in range(n + 1)]
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175