Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

True + True = 2. Elegantly perform boolean arithmetic?

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]]]

representing

([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.

like this:

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]

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 that's not as expected

True * True = 1 that's as expected

False + False = 0 that's as expected

False * False = 0 that's as expected

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?

like image 837
lo tolmencre Avatar asked Jul 08 '16 23:07

lo tolmencre


People also ask

Why True True is 2?

operator performs a strict comparison so it checks both value and type but since true is a boolean and 1 is a number they are not strictly equal thus the expression is true.

What is boolean arithmetic?

Boolean algebra (named after the mathematician George Boole) is a form of arithmetic that deals solely in ones and zeroes. It has only three operators: addition, multiplication and negation. As we shall see these correspond to OR, AND and NOT respectively.

What is the result of true true in Python?

python - True + True = 2.

Is true a boolean in Python?

Python Boolean TypeThe boolean value can be of two types only i.e. either True or False.


2 Answers

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

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


From 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.

like image 163
xgord Avatar answered Oct 16 '22 23:10

xgord


There is a way to do boolean arithmetic. That way is to use boolean operators.

  • and, as you call "*", is and.
  • or, as you call "+", is or.
like image 25
recursive Avatar answered Oct 16 '22 23:10

recursive