代码之家  ›  专栏  ›  技术社区  ›  Luke404

如何检查列表中元素之间的约束/这是约束编程吗?

  •  6
  • Luke404  · 技术社区  · 16 年前

    • 如果有一个元素foo=A,[B,C,D]中就不能有foo的元素
    • 如果有一个元素foo=X,那么必须至少有一个元素foo在[Y,Z]
    • 最小和最大元素之间可以有foo=BAR

    中堂进近应为:

    R_CONFLICT={ A: [B,C,D] }
    R_DEPENDS ={ X: [ [Y,Z], W, .. } # means: A depends on either Y or Z, and W
    R_MIN     ={BAR: n, BAZ: m}
    R_MAX     ={BAR: o, BAZ: p}
    # now just loop over lists to check them..
    

    这是一个问题吗 Constraint programming ? 我其实不需要 解决

    值得一提的是,我正在用Python编写代码,但我欢迎一个通用的编程答案:)如果结果证明我必须深入研究约束编程,我可能会从尝试开始 python-constraint .

    1 回复  |  直到 16 年前
        1
  •  4
  •   Chris    16 年前

    简短回答-是的,这可以检查使用约束编程,实际上你是提供一个解决方案,并检查它对约束,而不是让解算器搜索领域的潜力匹配的解决方案。这使得约束编程过于繁琐,特别是如果您使用Python,它可以很容易地检查这些条件。

    conflict = set([B, C , D])
    foos = set([x.foo for x in list])
    if A in foos:
        if len(foos & conflict): #Set intersection
             return false
    
    len([x for x in list where x.foo == BAR]) #Gives you number of occurances of BAR
    

    基本上我会说除非约束变得更复杂或者你想找到解决方案而不是仅仅测试,否则我会坚持使用代码而不是约束编程。