I am using Python and Sympy.
I have the following:
x,y,z = Symbols('x,y,z')
doc = {x : False, y : True, z: True}
rule = Or(x, And(y,z))
I am looking for a function in Sympy that will return True
on rule.eval(doc)
?
Edit: Currently I am using rule.subs
and rule.xreplace
both are performing slowly with about 0.0003 seconds per call. This makes it impractical.
A way to get better performance with minimal coding is to use lambdify
:
X = tuple(doc.iterkeys())
f = lambdify(X, rule)
After this IPython gave me:
V = tuple(doc.itervalues())
%timeit f(*V)
The slowest run took 7.56 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 209 ns per loop
I am not sure how much the warning may impact the conclusion, but there is a clear improvement. On the same computer I had with the original code:
%timeit rule.xreplace(doc)
10000 loops, best of 3: 126 µs per loop
And subs was even slower.
Rather than using subs can you use direct evaluation?
>>> F = Lambda((x, y, z), Or(x, And(y, z)))
>>> F(0, 1, 1)
True
If not, could you create a toy class that will allow subs via the lambda form? This is not a class but it gives the idea:
>>> def sub(f, d):
... F = Lambda(d.keys(), f)
... return F(*[d[k] for k in d.keys()])
>>> sub(Or(x,And(y,z)),{x:0,y:1,z:1})
The class would create the Lambda form and have a subs method which would return the evaluated Lambda form.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.