PySCIPOpt  5.1.1
Python Interface for the SCIP Optimization Suite
sudoku.py
Go to the documentation of this file.
1 
3 
4 # !/usr/bin/env python
5 
6 from pyscipopt import Model, quicksum
7 
8 # initial Sudoku values
9 init = [5, 3, 0, 0, 7, 0, 0, 0, 0,
10  6, 0, 0, 1, 9, 5, 0, 0, 0,
11  0, 9, 8, 0, 0, 0, 0, 6, 0,
12  8, 0, 0, 0, 6, 0, 0, 0, 3,
13  4, 0, 0, 8, 0, 3, 0, 0, 1,
14  7, 0, 0, 0, 2, 0, 0, 0, 6,
15  0, 6, 0, 0, 0, 0, 2, 8, 0,
16  0, 0, 0, 4, 1, 9, 0, 0, 5,
17  0, 0, 0, 0, 8, 0, 0, 7, 9]
18 
19 m = Model()
20 
21 # create a binary variable for every field and value
22 x = {}
23 for i in range(9):
24  for j in range(9):
25  for k in range(9):
26  name = str(i) + ',' + str(j) + ',' + str(k)
27  x[i, j, k] = m.addVar(name, vtype='B')
28 
29 # fill in initial values
30 for i in range(9):
31  for j in range(9):
32  if init[j + 9 * i] != 0:
33  m.addCons(x[i, j, init[j + 9 * i] - 1] == 1)
34 
35 # only one digit in every field
36 for i in range(9):
37  for j in range(9):
38  m.addCons(quicksum(x[i, j, k] for k in range(9)) == 1)
39 
40 # set up row and column constraints
41 for ind in range(9):
42  for k in range(9):
43  m.addCons(quicksum(x[ind, j, k] for j in range(9)) == 1)
44  m.addCons(quicksum(x[i, ind, k] for i in range(9)) == 1)
45 
46 # set up square constraints
47 for row in range(3):
48  for col in range(3):
49  for k in range(9):
50  m.addCons(quicksum(x[i + 3 * row, j + 3 * col, k] for i in range(3) for j in range(3)) == 1)
51 
52 m.hideOutput()
53 m.optimize()
54 
55 if m.getStatus() != 'optimal':
56  print('Sudoku is not feasible!')
57 else:
58  print('\nSudoku solution:\n')
59  sol = {}
60  for i in range(9):
61  out = ''
62  for j in range(9):
63  for k in range(9):
64  if m.getVal(x[i, j, k]) == 1:
65  sol[i, j] = k + 1
66  out += str(sol[i, j]) + ' '
67  print(out)
pyscipopt.expr.quicksum
def quicksum(termlist)
Definition: expr.pxi:357