Question: my output keeps getting No optimal solution but it has one and I need it to solve my sudoku puzzle here's my code to
my output keeps getting No optimal solution" but it has one and I need it to solve my sudoku puzzle here's my code to help fix:
import pyomo.environ as pyo
# Define the model and grid parameters
model pyo.ConcreteModel
N # Grid size for standard Sudoku
valuesrange range N
rowsrange rangeN
colsrange rangeN
# Decision variable: xr c n is if number n is in cell r c otherwise
model.x pyo.Varrowsrange, colsrange, valuesrange, domainpyo.Binary
model.constraints pyo.ConstraintList
# Constraint : Each cell contains one number
for r in rowsrange:
for c in colsrange:
model.constraints.addsummodelxr c n for n in valuesrange
# Constraint : Each row contains unique values
for r in rowsrange:
for n in valuesrange:
model.constraints.addsummodelxr c n for c in colsrange
# Constraint : Each column contains unique values
for c in colsrange:
for n in valuesrange:
model.constraints.addsummodelxr c n for r in rowsrange
# Constraint : Each x block contains unique values
sqrtN
for br in range N sqrtN:
for bc in range N sqrtN:
for n in valuesrange:
model.constraints.add
summodelxr c n for r in rangebr br sqrtN for c in rangebc bc sqrtN
# Constraint : Prefilled values
prefilledcells
for r c n in prefilledcells:
model.constraints.addmodelxr c n
# Solve the model
result pyo.SolverFactoryglpksolvemodel
# Print results
if result.solver.terminationcondition pyo.TerminationCondition.optimal:
printSolved Sudoku Puzzle:"
for r in rowsrange:
row
for c in colsrange:
for n in valuesrange:
if model.xr c n:
row.appendn
break
printjoinstrnum for num in row
else:
printNo optimal solution found."
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
