【问题标题】:Writing a Boolean Expression using Python [duplicate]使用 Python 编写布尔表达式 [重复]
【发布时间】:2016-11-21 11:47:39
【问题描述】:

我正在尝试在 Python 中编写一个布尔表达式,但似乎 Python 只能使用位运算执行 XOR 表达式。

在没有 XOR 运算符的情况下用 Python 编写此表达式的最佳方法是什么。

(A ^ B ^ C ^ D) U ((B U C U D)' XOR A)

编辑:

我已经尝试过:

if (A and B and C and D) or ((A and not (B or C or D)) or (not A and (B and C and D))):

我希望简化它。

【问题讨论】:

  • 你尝试了什么?
  • 查看python wikibitwise operators上有一个不错的页面。
  • 通过一些修改,您实际上可以写出来。如果您不想使用二进制表达式,一个想法是使用 set 库。

标签: python boolean-logic boolean-expression


【解决方案1】:

只需使用按位 ^ 运算符。当^-ed 在一起时,Python 的布尔值返回一个布尔值:

>>> True ^ True
False
>>> True ^ False
True

andor 运算符的存在主要是为了支持短路,但 XOR 不能短路。

还有!=:

>>> True != True
False
>>> True != False
True

但是当与更多参数链接时,这并不能达到你想要的效果:

>>> True != True != True
False

【讨论】:

    【解决方案2】:

    (A and B and C and D) or ((A and not (B or C or D)) or (not A and (B and C and D))) 将简化为: (B and C and D) or (A and not (B or C or D))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 2012-05-17
      • 2019-03-12
      • 2018-06-06
      • 1970-01-01
      相关资源
      最近更新 更多