【问题标题】:Optapy having problems with constraints (groupBy and sum)Optapy 存在约束问题(groupBy 和 sum)
【发布时间】:2021-12-28 12:31:51
【问题描述】:

刚开始测试 optapy,尝试使用 optapy、groupBy 和 sum 时出错:

TypeError: 'function' 对象不可迭代"

可能是求和的论据。有什么帮助吗?

def lecturer_teaching_load(constraint_factory: ConstraintFactory):
    print("Restricting by Teaching Load")
    return constraint_factory.forEach(SubjectClass) \
        .groupBy(lambda subject: subject.lecturer, sum(lambda subject: subject.teaching_load)) \
        .filter(lambda lecturer, load: lecturer.real_cap > load) \
        .penalize("Capacity conflict", HardSoftScore.ONE_HARD)

如果为同一位讲师计划的科目过多,则进行处罚。

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 我知道 Chris 一直在改进其中一些传递函数的 CS 案例。这是哪个版本的 optapy?

标签: group-by sum constraints optapy


【解决方案1】:

这里的主要问题是您使用的是 python 内置的 sum 函数(它接受一个迭代,并返回一个数字),而不是 ConstraintCollectors.sum 函数(它接受一个函数,并返回一个 ConstraintCollector)。

JPype 目前无法在没有显式转换的情况下区分函数重载,因此目前您需要将 sum 内的 lambda 转换为正确的类型(在本例中为 java.util.function.ToIntFunction)。这是自动为Joiners 完成的,但不是ConstraintCollectors(它在不同的地方使用各种不同的类型,使得在不复制 API 的情况下更难以自动化流程)。这段代码应该可以工作:

from optapy.constraint import ConstraintCollectors
from java.util.function import ToIntFunction

def lecturer_teaching_load(constraint_factory: ConstraintFactory):
    print("Restricting by Teaching Load")
    return constraint_factory.forEach(SubjectClass) \
        .groupBy(lambda subject: subject.lecturer, ConstraintCollectors.sum(ToIntFunction @ (lambda subject: subject.teaching_load))) \
        .filter(lambda lecturer, load: lecturer.real_cap > load) \
        .penalize("Capacity conflict", HardSoftScore.ONE_HARD)

【讨论】:

    猜你喜欢
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多