Skip to main content
 首页 » 编程设计

python之True + True = 2. 优雅地执行 boolean 运算

2025年05月04日16mfrbuaa

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

[[[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_value 在求和后为 True,则该子句作为一个整体为真。

但我没有得到我所期望的:

True + True = 2 这不是预期的

True * True = 1 符合预期

False + False = 0 符合预期

False * False = 0 符合预期

所以...True 就是 1,False 就是 0...真糟糕,我希望算术运算符会为 boolean 代数重载。有没有一种优雅的方法可以用 boolean 变量进行 boolean 算术运算?

请您参考如下方法:

在 Python 中,True == 1 和 False == 0,因为 True 和 False 是类型bool,它是 int 的子类型。当您使用运算符 + 时,它会隐式地添加 True 和 False 的整数值。

int(True) 
# 1 
 
int(False) 
# 0 

您真正想要的是将 True 和 False 视为二进制数。

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.