8
$\begingroup$

I'm trying to write an optimization model using an open-source solver's Python API. I'm new to use Python. The model objective function is as follows:

\begin{equation} \sum_{k=1}^{K} \sum_{j=1}^{n}\left(f_{k}+c_{0, j}^{k}\right) x_{0, j}^{k}+\sum_{k=1}^{K} \sum_{i=1}^{n} \sum_{j \in\{0, \ldots, n\} \backslash\{i\}} c_{i j}^{k} x_{i j}^{k} \end{equation}

where $(i, j, k)$ are indices, $x$ is a variable and $c,f$ are given parameters. In the second term of the objective function, there is a specific filter on the $j$ index. Doing this filter using C++/Java is easy. I was wondering, how can I do that in Python?

The snippet Python code is:

minimize (sum(c(k,i,j)*x[k][i][j] for k in range(K) for i in range(n) for j in range(n)))
$\endgroup$
2
  • 1
    $\begingroup$ In your math, you have i going from 1 to n and j going from 0 to n, but in your code, you have both going from 0 to n-1. What behavior is intended? $\endgroup$ Sep 13, 2019 at 20:34
  • $\begingroup$ @Acccumulation, thanks so much for your attention. As I mentioned, this was The snippet code. I will try to fix it. :) $\endgroup$
    – A.Omidi
    Sep 13, 2019 at 21:23

1 Answer 1

8
$\begingroup$

Easy:

minimize (sum(c(k,i,j)*x[k][i][j] for k in range(K) for i in range(n) for j in range(n) if j != i))

But note that your sums start from indices $1$ and end at $n$, while range(n) gives you $0$ to $n-1$.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.