True + True = 2.优雅地执行布尔运算? [英] True + True = 2. Elegantly perform boolean arithmetic?

查看:14
本文介绍了True + True = 2.优雅地执行布尔运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代表 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 == 1False == 0,为 TrueFalsebool 类型,它是 int 的子类型.当您使用运算符 + 时,它会隐式添加 TrueFalse 的整数值.

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

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

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 &是的

执行按位与".输出的每一位为 1,如果x与y的对应位为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 |是的

执行按位或".如果对应的位为 0,则输出的每一位为 0x AND of y 为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆