Search code examples
pythonpython-3.xlist-comprehensionor-tools

KeyError: (1, 1) when trying to use python list comprehension and google- ortools


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, '')

Solution

  • 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)]