Boolean operation with symbol in Sympy

烂漫一生 提交于 2019-12-24 14:33:00

问题


Boolean operation of a Boolean variable on a symbol produces TypeError, but the reverse has no problem:

>>> from sympy import *
>>> x = Symbol('x', bool=True)
>>> x ^ True
Not(x)
>>> True ^ x

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    True ^ x
TypeError: unsupported operand type(s) for ^: 'bool' and 'Symbol'

I can do try-catch:

try :
    print True ^ x
except TypeError:
    print x ^ True

Not(x)

But, for my present task, it is impossible to implement this with try-except as I have to deal with ~200 symbols. How can I achieve this?


回答1:


This is a bug, and it has been fixed in the development version of SymPy, and will be fixed in the next version. If you can't use the git version and can't wait, a workaround would be to monkeypatch __rxor__ (and so on) in sympy.logic.boolalg.Boolean to be equal to sympy.logic.boolalg.Boolean.__xor__.

In [1]: from sympy.logic.boolalg import Boolean

In [2]: Boolean.__rxor__ = Boolean.__xor__

In [3]: True ^ x
Out[3]: ¬ x

By the way, Symbol('x', bool=True) does nothing. It adds the assumption x.is_bool to the Symbol, but since that isn't a real assumption that SymPy knows about, it doesn't do anything.




回答2:


This is ugly, but it should do what you want:

expressions = [
  r'S[15] ^ (S[19] & S[72]) ^ S[112]',
]

for e in expressions:
  try:
    eval(e) # Do your thing
  except TypeError:
    pass


来源:https://stackoverflow.com/questions/19703284/boolean-operation-with-symbol-in-sympy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!