Files
ortools-clone/ortools/sat/samples/simple_sat_program.py

61 lines
1.7 KiB
Python
Raw Normal View History

2021-04-16 00:21:07 +02:00
#!/usr/bin/env python3
2025-01-10 11:35:44 +01:00
# Copyright 2010-2025 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
2022-06-22 17:51:14 +02:00
# [START program]
2021-10-18 14:24:28 +02:00
"""Simple solve."""
# [START import]
from ortools.sat.python import cp_model
2025-06-02 14:25:50 +02:00
2021-10-18 14:24:28 +02:00
# [END import]
2023-11-17 11:56:36 +01:00
def simple_sat_program():
"""Minimal CP-SAT example to showcase calling the solver."""
# Creates the model.
# [START model]
model = cp_model.CpModel()
# [END model]
# Creates the variables.
# [START variables]
num_vals = 3
2023-11-16 19:46:56 +01:00
x = model.new_int_var(0, num_vals - 1, "x")
y = model.new_int_var(0, num_vals - 1, "y")
z = model.new_int_var(0, num_vals - 1, "z")
# [END variables]
# Creates the constraints.
# [START constraints]
2023-11-16 19:46:56 +01:00
model.add(x != y)
# [END constraints]
# Creates a solver and solves the model.
# [START solve]
solver = cp_model.CpSolver()
2023-11-16 19:46:56 +01:00
status = solver.solve(model)
# [END solve]
2021-10-18 14:24:28 +02:00
# [START print_solution]
2021-10-18 15:47:31 +02:00
if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
2023-11-16 19:46:56 +01:00
print(f"x = {solver.value(x)}")
print(f"y = {solver.value(y)}")
print(f"z = {solver.value(z)}")
2021-10-18 14:24:28 +02:00
else:
print("No solution found.")
2021-10-18 14:24:28 +02:00
# [END print_solution]
2023-11-17 11:56:36 +01:00
simple_sat_program()
# [END program]