python布尔符号_在Sympy符号布尔运算

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 "", line 1, in

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值