Skip to content

Instantly share code, notes, and snippets.

@MaxvanHaastrecht
Created December 28, 2021 15:26
Show Gist options
  • Save MaxvanHaastrecht/67799f674fd84735b8b13f0248eab607 to your computer and use it in GitHub Desktop.
Save MaxvanHaastrecht/67799f674fd84735b8b13f0248eab607 to your computer and use it in GitHub Desktop.
Creating a TSP ILP in PuLP
import pulp as pl
# Define PuLP model
model = pl.LpProblem('TSP', pl.LpMinimize)
# Define binary variables
x = pl.LpVariable.dicts('x', ((i, j) for i in range(n_perm) for j in range(n_perm)), cat = 'Binary')
# Set the objective function
model += pl.lpSum(cost_dict[permutations[i], permutations[j]] * x[i, j] for i in range(n_perm) for j in range(n_perm))
# Define the constraints
for i in range(n_perm):
# Do not allow loops
model += x[i, i] == 0
for i in range(n_perm):
# Exactly one outgoing edge
model += pl.lpSum(x[i, j] for j in range(n_perm)) == 1
# Exactly one incoming edge
model += pl.lpSum(x[j, i] for j in range(n_perm)) == 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment