From 3ed1c5d0e4018fc70012a6209a859a059f7127b5 Mon Sep 17 00:00:00 2001 From: zhang Date: Fri, 25 Mar 2022 00:11:34 +0800 Subject: =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ordemo/two_sum.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 ordemo/two_sum.py (limited to 'ordemo/two_sum.py') diff --git a/ordemo/two_sum.py b/ordemo/two_sum.py new file mode 100644 index 0000000..5652998 --- /dev/null +++ b/ordemo/two_sum.py @@ -0,0 +1,36 @@ +from ortools.sat.python import cp_model + + +class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback): + """Print intermediate solutions.""" + + def __init__(self, variables): + cp_model.CpSolverSolutionCallback.__init__(self) + self.__variables = variables + self.__solution_count = 0 + + def on_solution_callback(self): + self.__solution_count += 1 + for v in self.__variables: + print('%s=%i' % (v, self.Value(v)), end=' ') + print() + + def solution_count(self): + return self.__solution_count + + +l = [2, 7, 1, 3, 6, 9, 10, -1, 12, 22] +target = 9 + +model = cp_model.CpModel() + +xs = [model.NewBoolVar(str(i)) for i in range(len(l))] + +model.Add(sum(xs) == 2) + +model.Add(sum([xs[i]*l[i] for i in range(len(l))]) == target) +solver = cp_model.CpSolver() +solution_printer = VarArraySolutionPrinter(xs) +solver.parameters.enumerate_all_solutions = True +solver.Solve(model, solution_printer) + -- cgit v1.2.3