You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google OR-Tools中统计变量取值的出现次数?

解决OR-Tools中统计变量取值出现次数的问题

要统计diff变量各取值的出现次数,你需要修改自定义的VarArraySolutionPrinter类——因为OR-Tools在找到每个可行解时都会触发on_solution_callback方法,正好可以在这里记录变量取值的计数。

修改后的完整代码

from ortools.sat.python import cp_model
from collections import defaultdict

model = cp_model.CpModel()
x = model.NewIntVar(0, 10, 'x')
y = model.NewIntVar(0, 10, 'y')
diff = model.NewIntVar(-10, 10, 'diff')
model.Add(diff == x - y)

# 重写Solution Printer类,增加计数功能
class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback):
    """打印中间解并统计diff变量的取值次数"""

    def __init__(self, variables, diff_var):
        cp_model.CpSolverSolutionCallback.__init__(self)
        self.__variables = variables
        self.__diff_var = diff_var  # 传入要统计的diff变量
        self.__solution_count = 0
        self.diff_counts = defaultdict(int)  # 用字典存储各取值的出现次数

    def on_solution_callback(self):
        self.__solution_count += 1
        # 记录当前diff的取值
        current_diff = self.Value(self.__diff_var)
        self.diff_counts[current_diff] += 1
        # 打印当前解(可选,不需要的话可以注释掉)
        for v in self.__variables:
            print(f"{v}={self.Value(v)}", end=" ")
        print()

    def solution_count(self):
        return self.__solution_count

    def print_diff_stats(self):
        """打印diff变量各取值的统计结果"""
        print("\ndiff变量取值统计:")
        for val in sorted(self.diff_counts.keys()):
            print(f"diff={val} 出现次数:{self.diff_counts[val]}")

solver = cp_model.CpSolver()
solver.parameters.enumerate_all_solutions = True
# 初始化时传入要统计的diff变量
solution_printer = VarArraySolutionPrinter([x, y, diff], diff)
status = solver.Solve(model, solution_printer)

# 求解完成后打印统计结果
solution_printer.print_diff_stats()

关键修改说明

  • 在类的初始化方法中,新增diff_var参数传入需要统计的变量;同时用defaultdict存储计数,无需提前定义所有可能的取值。
  • 在on_solution_callback中,每次找到解时获取当前diff的取值,更新对应计数。
  • 新增print_diff_stats方法,在求解完成后输出所有取值的出现次数。
  • 保留了原有的打印中间解功能,不需要的话可直接注释对应代码块。

运行结果示例

程序会先打印所有可行解,最后输出类似这样的统计:

diff变量取值统计:
diff=-10 出现次数:1
diff=-9 出现次数:2
...
diff=0 出现次数:11
...
diff=9 出现次数:2
diff=10 出现次数:1

内容的提问来源于stack exchange,提问作者thehumbling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:37:13