True + True = 2. 优雅地执行布尔运算?

True + True = 2. Elegantly perform boolean arithmetic?

我有代表 SAT 论坛的真值嵌套列表,如下所示:

[[[0, True, False], [0, True, False], [0, True, 1]], [[0, True, True], [2, True, True], [3, False, True]], [[1, False, False], [1, False, False], [3, False, True]]]

代表

([x0=0] + [x0=0] + [x0=1]) * ([x0=1] + [x1=1] + [-x2=1]) * ([-x3=0] + [-x3=0] + [-x2=1])

我想计算整个公式的真值。第一步是将每个子句中文字的真值相加。

像这样:

clause_truth_value = None

for literal in clause:
    # multiply polarity of literal with its value
    # sum over all literals
    clause_truth_value += literal[1]*literal[2]

如果求和后clause_truth_valueTrue,则该子句整体为真。

但我没有得到预期的结果:

True + True = 2 不符合预期

True * True = 1符合预期

False + False = 0符合预期

False * False = 0符合预期

所以... True 就是 1,False 就是 0... 太糟糕了,我预计算术运算符会为布尔代数重载。有没有一种优雅的方法可以用布尔变量做布尔算术?

有一种方法可以进行布尔运算。那种方式就是使用布尔运算符。

  • 并且,正如您所说的“*”,是 and
  • 或者,如您所说的“+”,是 or

在Python、True == 1False == 0中,因为TrueFalse是类型bool,是[的子类型=17=]。当您使用运算符 + 时,它会隐式地添加 TrueFalse.

的整数值
int(True)
# 1

int(False)
# 0

您真正想要的是将 TrueFalse 视为二进制数。

int(False & False)
# 0

int(True & False)
# 0

int(True & True)
# 1


来自 Bitwise Operators in Python:

x & y

Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.

x | y

Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.