#!/usr/bin/python # Copyright 2016, Gurobi Optimization, Inc. import sys import math from gurobipy import * # Read the input file f = open(sys.argv[1]) grid = f.read().split() n = len(grid[0]) s = int(math.sqrt(n)) # array of variables will be indexed by (i,j,v) tuples vars = {} # Create our array of model variables model = Model('sudoku') for i in range(n): for j in range(n): for v in range(n): vars[i,j,v] = model.addVar(vtype=GRB.BINARY, name='G_'+ str(i)+'_'+str(j)+'_'+str(v)) # Update model to integrate new variables model.update() # Create instance given in the input for i in range(n): for j in range(n): if grid[i][j] != '.': v = int(grid[i][j]) - 1 model.addConstr(vars[i,j,v] == 1, 'Fix_' + str(i) + '_' + str(j)) # Model your constraints here model.update() model.optimize() print('') print('Solution:') print('') # Retrieve optimization result solution = model.getAttr('X', vars) for i in range(n): sol = '' for j in range(n): for v in range(n): if solution[i,j,v] > 0.5: sol += str(v+1) print(sol)