3

I would like to match a pattern to an expression in such a way that returns all possible matchings. Using SymPy I can match my pattern to my expression in a single arbitrarily selected way. How can I use pattern matching to obtain the entire set (up to arbitrary renamings)

Currently I can do this

>>> p, q = Wild('p'), Wild('q')
>>> x, y, z = symbols('x,y,z')

>>> (p+q).matches(x+y+z)
{p: y + z, q: x}

I want to do this

>>> (p+q).allmatches(x+y+z)
{{p: x, q: y + z}, {p: y, q: x + z}, {p: z, q: x + y}}

Note that each possible partitioning is represented. I would be willing to implement this myself. What are standard algorithms for pattern matching that produce all possible matches?

4

1 回答 1

2

我认为您必须使用所有可能的排除组来定位匹配项,例如

In [16]: [(x + y + z).match(Wild('p', exclude=i) + Wild('q', exclude=set([x, y, z]) - set(i))) for i in subsets([x, y, z])]
Out[16]: [{p: x + y + z, q: 0}, {p: y + z, q: x}, {p: x + z, q: y}, {p: x + y, q: z}, {p: z, q: x + y}, {p: y, q: x + z}, {p: x, q: y + z}, {p: 0, q: x + y + z}]

subsets是来自 的 SymPy 函数sympy.utilities.iterables)。

于 2012-10-24T06:24:20.613 回答