基于条件的快速匹配元组

| 我正在寻找以下问题的快速算法。 规则由有关元组的子句的组合表示。子句指定两个元组项目之间的关系。例如,“ 0”表示:“ 1”。 因此,规则可能是:
T(1)[2] = T(3)[1] AND T(1)[1] > T(2)[1]
通用规则: 条款:
(T(j)[i] op T(k)[l])
条件:
Clause (AND Clause)*
支持的运算符:
=
!=
>
<
<=
>=
该算法接收这样的规则和一个元组列表,其中每个项目都是一个数字:
(i11 i12 ... i1n)
...
(ik1 ik2 ... ikm)
元组的长度不同,其数量未知。列表中的元组可以按任何顺序排列。 该算法将从匹配规则的输入中输出所有元组组合。 例: 规则:
T(1)[1] = T(2)[1] AND T(1)[3]>T(3)[1]
元组:
`(1 2 3 4)`   T1
`(3 2 4)\'     T2
`(4)`         T3
`(1 5 3 6 7)` T4
将输出以下组合:
T(1): T1, T(2): T4, T(3): T2
T(1): T4, T(2): T1, T(3): T2
基本上,它将确定哪些元组可以替代每个T(i),以便其规则成立。 是否有众所周知的算法可以快速执行此操作?有什么建议么? 谢谢, 一种     
已邀请:
由于您需要列出所有可能的分配,而不是计算它们的数量,例如,这可能会更容易(尽管我不这么认为),所以唯一的方法可能是实施回溯解决方案。 编辑:具体来说,由于原始列表有
N!
个排列(其中
N
是元组的数量),可能满足约束条件(在最坏的情况下),因此您需要列出它们,因此
O(N!)
的上限很严格。     
我认为您正在使用Rete算法寻找与Beta网络类似的东西http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.83.4551&rep=rep1&type=pdf     
您可以将其实现为
constraint
模块的包装器。这是您问题中示例的解决方案:
#!/usr/bin/env python
from constraint import AllDifferentConstraint, Problem

number_of_variables = 3
variables = [\"T(%d)\" % i for i in range(1, number_of_variables+1)]
possible_values = [(1, 2, 3, 4), (3, 2, 4), (4,), (1, 5, 3, 6, 7)]

problem = Problem()
problem.addVariables(variables, possible_values)
# each tuple should occur only once in the solution
problem.addConstraint(AllDifferentConstraint(), variables)
# T(1)[1] = T(2)[1] rule
problem.addConstraint(lambda a, b: len(a) > 0 and len(b) > 0 and a[0] == b[0],
                      \"T(1) T(2)\".split())
# T(1)[3] >= T(3)[1] rule 
problem.addConstraint(lambda a, b: len(a) > 2 and len(b) > 0 and a[2] >= b[0],
                      \"T(1) T(3)\".split()) # implicit AND

short_names = dict((val, \"T%d\" % i) for i, val in enumerate(possible_values, 1))
for solution in problem.getSolutionIter():
    print \", \".join(\"%s: %s\" % (variable, short_names[value])
                    for variable, value in sorted(solution.iteritems()))
输出量
T(1): T4, T(2): T1, T(3): T2
T(1): T1, T(2): T4, T(3): T2
您可以将规则合并为单个约束:
# T(1)[1] = T(2)[1] AND T(1)[3] >= T(3)[1]
problem.addConstraint(lambda a, b, c: (len(a) > 2 and b and c and
                                       a[0] == b[0] and a[2] >= c[0]),
                      variables)
要安装“ 19”模块,请输入: $ pip安装http://labix.org/download/python-constraint/python-constraint-1.1.tar.bz2     

要回复问题请先登录注册