True + True =2.优雅地执行布尔算术? [英] True + True = 2. Elegantly perform boolean arithmetic?
问题描述
我有嵌套的真值列表,它们代表SAT论坛,例如:
I have nested lists of truth values representing SAT forumlas, like this:
[[[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])
我想计算整个公式的真值.第一步是将每个子句中文字的真值相加.
I would like to calculate the truth value of the whole formula. First step would be adding up the truth values of the literals in each clause.
像这样:
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
,则该子句在整体上为真.
if clause_truth_value
is True
after the summation, the clause is true as a whole.
但是我没有得到我所期望的:
But I am not getting what I expected:
True + True = 2
与预期不符
True * True = 1
符合预期
False + False = 0
符合预期
False * False = 0
符合预期
所以... True仅是1而False是0 ...很烂,我希望算术运算符会因布尔代数而重载.有没有一种优雅的方法可以对布尔变量进行布尔算术?
so... True is simply 1 and False is 0... that sucks, I expected the arithmetic operators to be overloaded for the boolean algebra. Is there an elegant way to do do boolean arithmetic with boolean variables?
推荐答案
在Python中,True == 1
和False == 0
的类型分别为bool
和False
,而bool
是int
的子类型. .使用运算符+
时,它隐式地添加了True
和False
的整数值.
In Python, True == 1
and False == 0
, as True
and False
are type bool
, which is a subtype of int
. When you use the operator +
, it is implicitly adding the integer values of True
and False
.
int(True)
# 1
int(False)
# 0
您真正想要的是将True
和False
视为二进制数.
What you really want is to treat True
and False
as binary numbers.
int(False & False)
# 0
int(True & False)
# 0
int(True & True)
# 1
来自 Python中的按位运算符:
x& y
x & y
执行按位与".如果 y的x AND的对应位为1,否则为0.
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
执行按位或".如果输出的相应位为0,则输出的每个位均为0 y的x AND为0,否则为1.
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.
这篇关于True + True =2.优雅地执行布尔算术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!